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.
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
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.