Assuming I have the following shakespeare template code:

$doctype 5
<html>
    <body>
        <h2>This is a test
        <div>Value of test variable: #{testVariable}

in the file mytemplate.hamlet.

How can I render it using shamletFile without explicitly pasting the template in the source code?

Note: This question was answered immediately in a Q&A-Style manner and therefore intentionally does not show any research effort.

有帮助吗?

解决方案

See this previous question for information on how any why to render hamlet templates as static files.

The only major difference is that you need to use Template Haskell's $(...) operator to evaluate the Q Exp that is yielded by shamletFile. Here's a full example that assumes your mytemplate.hamlet is located in the same directory as your Haskell file:

{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Blaze.Html
import Text.Hamlet

-- | The main template
renderTemplate :: String -> String
renderTemplate testVariable = renderHtml ( $(shamletFile "mypage.hamlet") )

main = do
    putStrLn $ renderTemplate "foobar"

When executed, it prints:

<!DOCTYPE html>
<html><body><h2>This is a test</h2>
<div>Value of test variable: foobar</div>
</body>
</html>

Note that in your application you might need to use either shamletFile, xshamletFile, hamletFile or ihamletFile. See the Hackage documentation and the Yesod book on Shakespearean templates for information on when to use any of those.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top