用小村庄渲染静态HTML [英] Rendering static HTML with hamlet

查看:120
本文介绍了用小村庄渲染静态HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 hamlet 框架从Haskell内部生成静态HTML页面?

How can I use the hamlet framework to generate static HTML pages from inside Haskell?

注意:这个问题有意没有显示出研究成果.对于我的研究工作,请参见下面的问答式答案.

Note: This question intentionally doesn't show research effort. For my research effort, see the Q&A-style answer below.

推荐答案

hamlet产生QuasiQuoters,其评估为 表达式.使用 Text.Blaze.Html.Renderer.String.renderHtml 将它们呈现为字符串.

hamlet yields QuasiQuoters that are evaluated to blaze expressions. Using Text.Blaze.Html.Renderer.String.renderHtml you can render them to a string.

让我们从一个简单的非HTML示例开始:

Let's start with a simple non-HTML example:

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

greet name = [shamlet|Hello world #{name}|]
-- This prints "Hello world John Foo"
main = putStrLn $ renderHtml $ greet "John Foo"

为了提高效率,您还可以使用Text代替String

For increased efficiency, you could also use Text instead of String Text.Blaze.Html.Renderer.Text.renderHtml

将此内容写入文件与标准的Haskell方法没有什么不同.例如,可以使用writeFile代替putStrLn来执行此操作.您只需要修改最后一行

Writing this to a file is not different from the standard Haskell approach. You can do this, for example, by using writeFile instead of putStrLn. You only need to modify the last line

main = do writeFile "greet.txt" $ renderHtml $ greet "John Foo"

现在,我们只需要添加HTML标记,而无需使用纯文本.有关更多参考,请参见莎士比亚文档.

Now we only need to add HTML markup instead of using plain text. See the Shakespeare documentation for further reference.

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

greet name = [shamlet|
                $doctype 5
                <html>
                    <head>
                        <title>Greeting for #{name}
                    <body>
                        <h2>
                            Hello world #{name}|]

main = writeFile "greet.html" $ renderHtml $ greet "John Foo"

greet.html现在包含一个静态呈现的问候HTML.

greet.html now contains a statically rendered greeting HTML.

这篇关于用小村庄渲染静态HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆