【问题标题】:Render hamlet template from file从文件中渲染小村庄模板
【发布时间】:2014-02-06 16:58:54
【问题描述】:

假设我有以下shakespeare 模板代码:

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

在文件mytemplate.hamlet中。

如何在不将模板显式粘贴到源代码中的情况下使用shamletFile 渲染它?

注意:这个问题是立即以问答方式回答的,因此故意不显示任何研究工作。

【问题讨论】:

    标签: haskell hamlet


    【解决方案1】:

    请参阅this previous question,了解为什么要将hamlet 模板呈现为静态文件。

    唯一的主要区别是您需要使用 Template Haskell 的 $(...) 运算符来评估由 shamletFile 产生的 Q Exp。这是一个完整的示例,假设您的 mytemplate.hamlet 与您的 Haskell 文件位于同一目录中:

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

    执行时会打印:

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

    请注意,在您的应用程序中,您可能需要使用shamletFilexshamletFilehamletFileihamletFile。请参阅 the Hackage documentationthe Yesod book on Shakespearean templates 了解何时使用其中任何一个的信息。

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多