Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering static HTML with hamlet

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.

like image 716
Uli Köhler Avatar asked Mar 20 '23 20:03

Uli Köhler


1 Answers

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.

like image 143
Uli Köhler Avatar answered Apr 19 '23 20:04

Uli Köhler