Using Julius outside Yesod
I am trying to figure out how to emit Javascript using standalone Julius outside of Yesod:
{-# LANGUAGE QuasiQuotes #-}
import qualified Data.Text.Lazy.IO as LazyIO
import Text.Julius
main = do
let delta = 1 :: Int
LazyIO.putStrLn $ renderJavascript $ [julius|
function f(x) {
return x + #{delta};
}
|] undefined
But I am getting this error:
t2.hs:8:48:
No instance for (ToJavascript Integer)
arising from a use of ‘toJavascript’
In the expression: toJavascript delta
...
Please, help. I have no idea what is needed, I just started looking at Julius. If I remove the interpolation then it successfully removes the text.
source to share
Try the following:
import qualified Data.Text.Lazy.IO as LazyIO
import Text.Julius
import Data.Aeson
main = do
let delta = toJSON (1 :: Int)
LazyIO.putStrLn $ renderJavascript $ [julius|
function f(x) {
return x + #{delta};
}
|] undefined
Explanation:
The error message says it delta
must have an instance ToJavascript
. A search for the class ToJavascript
reveals that these instances are defined by default:
ToJavascript Bool
ToJavascript Value
ToJavascript RawJavascript
The absence of an instance Int
(or Integer
) explains the error message.
However, there is an instance Value
and with help toJSON
from the Aeson library we can turn it Int
into Value
.
source to share
Usage rawJS
should make it work:
{-# LANGUAGE QuasiQuotes #-}
import qualified Data.Text.Lazy.IO as LazyIO
import Text.Julius
main = do
let delta = rawJS $ show (1 :: Int)
LazyIO.putStrLn $ renderJavascript $ [julius|
function f(x) {
return x + #{delta};
}
|] undefined
Will produce:
function f(x) {
return x + 1
}
source to share