The simplest custom Hakyll compiler

Posted here in case it’s of use to others: Hakyll is a great Haskell-based tool for statically generating websites, but customizing your site sometimes means poking around the Hakyll API documentation, which can be a bit daunting for newcomers.

I needed a custom compiler for Hakyll, so that I could do some preprocessing of CSS files before they’re output. It took me a bit of reading of the API (and this post by Kjær Laustsen) to find the simplest way of making a compiler that simply transforms a string.

Here it is:

mkCompiler f = getResourceString >>= return . (fmap f)

Or, a bit more verbosely:

mkCompiler :: (String -> b) -> Compiler (Item b)
mkCompiler f = do
s <- getResourceString
return $ fmap f s

Given any function f mapping from a string to some type b, mkCompiler will give us a compiler that applies that function to the body of the file we’re processing. (And if we’re just doing a simple string-to-string transform, our function f will have type String -> String , obviously.)

For instance — we want to copy over a README file to our site for some reason, and want to add the text “foo!” at the end. In our main function, we can just add:

main = hakyll $ do
-- ...
match "README" $ do
route idRoute
compile $ mkCompiler (\x -> x ++ "foo!")

And voilà. It’s done.

programming stuff. Haskell and Ocaml, mostly