Adding comments to Hakyll

Posted on February 1, 2021

This blog is a static site generated by Hakyll and is hosted on GitLab Pages, so it cannot rely on any dynamic server-side processing support to store comments. Usually a static site addresses this problem by using an external service, I chose utteranc.es, it is opensource, fast and easy to customize, other features are described later.

Step 1

Let’s start building a fresh Hakyll site

% hakyll-init mysite
% cd mysite
% ls templates
archive.html  default.html  post.html  post-list.html

Step 2

utterances stores the comments in a public GitHub repository (nice feature!), so, now create a public repository, for example my is https://github.com/alfonsosiciliano/comments-alfonsosiciliano.gitlab.io; note the interoperability indeed this blog is in a GitLab repository.

Step 3

Go to https://utteranc.es and compile the form. An option allows to select “The mapping between blog posts and GitHub issues” indeed the comments are stored as iusses, the screenshot shows the generate iusses with “title”, “url” and “pathname”.

Finally copy the generated script.

Step 4

Open templates/post.html in mysite:

<article>
    <section class="header">
        Posted on $date$
        $if(author)$
            by $author$
        $endif$
    </section>
    <section>
        $body$
    </section>
</article>

and paste the script of utterances:

<article>
    <section class="header">
        Posted on $date$
        $if(author)$
            by $author$
        $endif$
    </section>
    <section>
        $body$
    </section>
</article>
<script src="https://utteranc.es/client.js"
        repo="accountGithub/commentPublicRepo"
        issue-term="pathname"
        theme="preferred-color-scheme"
        crossorigin="anonymous"
        async>
</script>

Step 5

Now every post in the post/ directory will have a comment form. For filtering posts with comments we could use its header adding a comment key:

---
title: Adding comments to Hakyll
comment: trueOrWhatever
---
...post...

We need to update templates/posts.html again for adding $if(comment)$ and $endif$:

<article>
    <section class="header">
        Posted on $date$
        $if(author)$
            by $author$
        $endif$
    </section>
    <section>
        $body$
    </section>
</article>
$if(comment)$
<script src="https://utteranc.es/client.js"
        repo="accountGithub/commentPublicRepo"
        issue-term="pathname"
        theme="preferred-color-scheme"
        crossorigin="anonymous"
        async>
</script>
$endif$

Step 6

It’s all, Happy Blogging!