Scotty + Html -> 如何将它们交织在一起?

Scotty + Html -> how to intertwine them?

如何在 Scotty 中使用 html 页面,包括 html 模板?但不是通过 Blaze,因为我不喜欢在 haskell 代码中描述它的结构。它认为我应该抢劫,但如何将它与 Scotty 交织在一起?

您可以使用 Heist.renderTemplate 将模板转换为 Blaze.ByteString.Builder.Builder(这不是 blaze-html,我认为没问题),然后通过 Web.Scotty.raw 进行设置。例如:

{-# 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