Is there a less awkward way to use blaze-html with a Reader monad?

Viewed 883

The BlazeHtml tutorial suggests using a Reader monad for real-world templating with BlazeHtml, but without illustrating how this should be done. I tried following this recommendation. The result leaves me confused.

To illustrate, assume I have a simple User type, and I want to compose my HTML using separate functions, one for the layout, and another for a part of the HTML page where I display user information. If I use a Reader Monad, it looks like this:

data User = User {
    username :: Text
  , userId :: nt
  } deriving (Show)

userBox :: Reader User Html
userBox = do
  user <- ask
  return $ do
      dl $ do
        dt $ "Username"
        dd $ H.toHtml $ username user
        dt $ "UserId"
        dd $ H.toHtml $ userId user

page :: Reader User Html
page = do
  user <- ask
  return $ H.docTypeHtml $ do
    H.head $ title "Reader Monad Blaze Example"
    H.body $ do
      h1 $ "Hello world"
      runReader userBox user

Compare this to my version that doesn't use the Reader monad:

userBox :: User -> Html
userBox user = do
      dl $ do
        dt $ "Username"
        dd $ H.toHtml $ username user
        dt $ "UserId"
        dd $ H.toHtml $ userId user

page :: User -> Html
page user = do
  H.docTypeHtml $ do
    H.head $ title "Blaze Example, No Reader Monad"
    H.body $ do
      h1 $ "Hello world"
      userBox user

So I'm having trouble seeing how a Reader Monad can actually tighten up the templating code in real-world use cases. Am I missing something?

2 Answers

Blaze's Markup type is not a transformer, so it can't be used to transform a ReaderT.

type Markup = MarkupM ()
data MarkupM a

You can use the lucid package (tutorial here), like this:

$ stack build lucid
$ stack exec ghci
GHCi, version 8.2.2: http://www.haskell.org/ghc/  :? for help
> :set -XOverloadedStrings -XExtendedDefaultRules
> import Lucid
> import Control.Monad.Trans.Reader
> import Control.Monad.Trans
> runReaderT (renderTextT (do p_ (do title <- lift ask; strong_ (toHtml title)))) "Hi"
"<p><strong>Hi</strong></p>"
> 
Related