hakyll

How do I interpolate $key$s in a file without applying a template?


In Jekyll it is possible to have a file that looks like

---
title: Whatever
layout: null
---

<h1>{{ title }}</h1>

The {{ title }} will be interpolated, but the layout: null means that the file contents won’t be wrapped in any kind of template.

What is the equivalent in Hakyll? In other words, if I have a self-contained file like

<h1>$title$</h1>

what kind of block do I need to pass to compile in order to have the $title$ value interpolated, without wrapping the page’s contents in some template?


Solution

  • The answer (thanks to erasmas in the #hakyll channel!) is to compile your page using

    getResourceBody >>= applyAsTemplate theContext
    

    where theContext is the instance of Context String that contains the fields you want.

    Here’s a toy example of how you’d use this compiler:

    main :: IO ()
    main = hakyll $ do
        match "index.html" $ do
            route idRoute
            compile $ getResourceBody >>= applyAsTemplate indexContext
    
    indexContext :: Context String
    indexContext = mconcat
        [ constField "title" "My Website"
        , defaultContext
        ]