Rendering static HTML with hamlet

◇◆丶佛笑我妖孽 提交于 2019-12-10 16:33:43

问题


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.


回答1:


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

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"

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

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"

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 now contains a statically rendered greeting HTML.



来源:https://stackoverflow.com/questions/21313534/rendering-static-html-with-hamlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!