How to render a ginger template given template text and context with ToJSON?

Viewed 55

I am trying to use ginger library. My attempt based on the library documentation:

renderTemplate :: ToJSON c => Text -> c -> Either Text Text
renderTemplate template ctx = do
  tpl <- tplEither
  let ctxGVal :: GVal Identity = rawJSONToGVal $ toJSON ctx
  let r :: Text = easyRender ctxGVal tpl
  return r
  where
    tplEither :: Either Text (Template SourcePos)
    tplEither = parseGinger nullResolver Nothing (toS template) & runIdentity & mapLeft tshow
    nullResolver :: IncludeResolver Identity
    nullResolver = const $ return Nothing

I am getting:

Could not deduce (ToGVal
                          (Text.Ginger.Run.Type.Run
                             SourcePos (Control.Monad.Trans.Writer.Lazy.Writer Text) Text)
                          (GVal Identity))
        arising from a use of ‘easyRender’

I don't really understand what is going on. Why GVal needs a parameter at all? From the examples it looks to me it should be possible to render a template in a pure way.

How to modify my code so it compiles and works as intended (from given template and context produces text)?

1 Answers

To solve your problem you need to use GVal (Run SourcePos (Writer Text) Text) as the type of ctxGVal instead of GVal Identity.

The rawJSONToGVal function can produce any GVal m so you have to choose the m that is needed by the rendering function, your application of easyRender requires the type Run SourcePos (Writer Text) Text.

Related