11

Can anyone point me to an example of how to use Hamlet without Yesod? http://www.yesodweb.com/book/templates is a great bit of documentation, but I can't get my ghci session to render even a simple hamlet template without crashing.

singpolyma
  • 10,999
  • 5
  • 47
  • 71

2 Answers2

16

Here's an example showing most of the basic stuff, including rendering of typed URLs.

{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}

import Data.Text
import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Hamlet hiding (renderHtml)

data Url = Haskell | Yesod

renderUrl Haskell _ = pack "http://haskell.org"
renderUrl Yesod   _ = pack "http://www.yesodweb.com"

title = pack "This is in scope of the template below"

template :: HtmlUrl Url
template = [hamlet|
<html>
    <head>
        #{title}
    <body>
        <p>
            <a href=@{Haskell}>Haskell
            <a href=@{Yesod}>Yesod
|]

main = do
    let html = template renderUrl
    putStrLn $ renderHtml html

Output:

<html><head>This is in scope of the template below</head>
<body><p><a href="http://haskell.org">Haskell</a>
<a href="http://www.yesodweb.com">Yesod</a>
</p>
</body>
</html>
Roman Cheplyaka
  • 37,738
  • 7
  • 72
  • 121
hammar
  • 138,522
  • 17
  • 304
  • 385
  • Trying this as-is gives me this ghc compile error: http://pastie.org/2220259 if I change the @{} to #{} I get: http://pastie.org/2220261 – singpolyma Jul 15 '11 at 23:30
  • It works fine here running it with `runghc` using `ghc 7.0.2` and `hamlet 0.8.2`. How are you running this? The first error looks very strange. How did the language pragmas end up in the HTML? The second one looks like you just have to remove some of the `pack` calls. – hammar Jul 16 '11 at 00:23
  • that was trying to run ghc --make, trying runghc I get http://pastie.org/2220468 ghc 7.0.3 hamlet 0.6.1.2 -- oh, my version is quite a bit older than yours. perhaps the syntax has been changed :( – singpolyma Jul 16 '11 at 00:34
  • Ah, I've discovered it. Apparently hamlet used to be more like haml, and my version is that old syntax – singpolyma Jul 16 '11 at 00:40
3

Well, handwaving the URL rendering and doing things in the stupidest way that works, we can use this:

hamVal = [$hamlet| 
<html>
    <head>
        <title>Test page
    <body>Testing
|]

test :: ByteString
test = renderHamlet (\_ _ -> "") hamVal

Which works as expected. I imagine you want to do something slightly more useful, but the trivial example here works fine so it's hard to say more without knowing where you're having trouble.

jan.vogt
  • 1,801
  • 10
  • 27
C. A. McCann
  • 76,893
  • 19
  • 209
  • 302
  • So, I got this to compile, but suprisingly it outputs Test pageTesting instead of the expected converted-to-proper-html – singpolyma Jul 15 '11 at 23:36
  • Ah, I've discovered it. Apparently hamlet used to be more like haml, and my version is that old syntax – singpolyma Jul 16 '11 at 00:40