Search code examples
htmlhaskellscotty

Scotty + Html -> how to intertwine them?


How can I work with html pages, including html templates, in Scotty? But not via Blaze because I don't like describing its structure in haskell code. It think I should heist, but how exactly to intertwine it with Scotty?


Solution

  • You can use Heist.renderTemplate to turn a template into Blaze.ByteString.Builder.Builder (that's not blaze-html, I assume that's okay) and then set that via Web.Scotty.raw. For example:

    {-# LANGUAGE OverloadedStrings #-}
    import Heist
    import Heist.Interpreted
    
    import Web.Scotty (scotty, get, raw, setHeader)
    
    import Control.Monad.Trans.Either (runEitherT)
    import Control.Monad.IO.Class (liftIO)
    import Blaze.ByteString.Builder (toByteString)
    
    import qualified Data.ByteString.Lazy as DBL
    import qualified Data.Text.Lazy.Encoding as DT
    
    import Text.XmlHtml
    
    main = scotty 3000 $
        get "/" $ do
            -- normally you would probably load your templates from a file,
            -- but to keep the example small
            (Right heist) <- liftIO $ runEitherT $ initHeist emptyHeistConfig
            let heist' = addTemplate "foo" [TextNode "Hello world!"] Nothing heist
    
            (Just (builder, mime)) <- renderTemplate heist' "foo"
    
            setHeader "Content-Type" (DT.decodeUtf8 $ DBL.fromStrict mime)
            raw $ DBL.fromStrict $ toByteString builder