Hakyll snapshots for a complete post listing

October 9, 2021 - Tags: haskell, hakyll

On my Hakyll page I wanted to have the complete first 10 posts on the index page. Because I did not know what I was looking for, it took me a while to find it in the tutorial for RSS feeds. The trick is to save a snapshot before Hakyll introduces the default template:

  match "posts/*" $ do
    route $ setExtension "html"
    compile $
      pandocCompiler
        >>= loadAndApplyTemplate "templates/post.html" postCtx
        >>= saveSnapshot "content"
        >>= loadAndApplyTemplate "templates/default.html" postCtx
        >>= relativizeUrls

After that it’s easy to load the snapshots on the target for the index page:

match "index.html" $ do
  route idRoute
  compile $ do
    posts <- fmap (take 10) $ recentFirst =<< loadAllSnapshots "posts/*" "content"
    let ctx =
          listField "posts" postCtx (return posts)
            <> constField "title" "Home"
            <> defaultContext
    getResourceBody
      >>= applyAsTemplate ctx
      >>= loadAndApplyTemplate "templates/default.html" ctx
      >>= relativizeUrls

If you don’t use snapshots, not only the content of the post, but the complete page is pasted again, which was the case in my first, naive attempt.