Enabling giscus comments on all posts#

To avoid having to add the giscus comment snippet of the previous post to every post, I want to add it to the page template. To do this, we first need to set up Sphinx to look for custom templates, figure out a good starting template, and then modify it to our liking.

The first thing to do is create the _templates directory in the main folder of the project. Ensure the path of this folder is specified in conf.py by adding the following line templates_path = ["_templates"]. Next, we want to modify the main page.html template. Here, we take take the page.html template of the ablog repository as a starting point and place this in the template directory. When trying to build the website with this file we will encounter an error as it contains a relative import to ablog/postnavy.html. The easiest way to address this is to copy over ablog/postnavy.html to _templates/ablog/postnavy.html.

Next, we modify _templates/page.html to include our giscus snippet and get rid of the old disqus code. As not all my readers are familiar with GitHub I want to provide a small hint that they will need a GitHub account to comment so I add a small paragraph in the template.

The final page.html should look something like this:

{%- extends "layout.html" %}
{% set fa = ablog.fontawesome %}
{%- block extrahead %}
{{ super() }}
{% if feed_path %}
<link rel="alternate" type="application/atom+xml" href="{{ pathto(feed_path, 1) }}/atom.xml" title="{{ feed_title }}" />
{% endif %}
{% if ablog.fontawesome_link_cdn %}
<link href="{{ ablog.fontawesome_link_cdn }}" rel="stylesheet" />
{% elif ablog.fontawesome_css_file %}
<link rel="stylesheet" href="{{ pathto('_static/' + ablog.fontawesome_css_file, 1) }}" type="text/css" />
{% endif %}
{% endblock %}
{% block body %}
{{ body }}

<div class="section ablog__blog_comments">
    {% if pagename in ablog %}
    {% include "ablog/postnavy.html" %}
    {% endif %}
    {% if ablog.blog_baseurl and (not ablog[pagename].nocomments) and ((pagename in ablog and
    (ablog[pagename].published)) or (not pagename in ablog and ablog.disqus_pages)) %}
    <div class="section ablog__comments">
        <h2>Comments</h2>
        <script src="https://giscus.app/client.js"
            data-repo="[ENTER REPO HERE]"
            data-repo-id="[ENTER REPO ID HERE]"
            data-category="[ENTER CATEGORY NAME HERE]"
            data-category-id="[ENTER CATEGORY ID HERE]"
            data-mapping="pathname"
            data-strict="0"
            data-reactions-enabled="1"
            data-emit-metadata="0"
            data-input-position="bottom"
            data-theme="preferred_color_scheme"
            data-lang="en"
            crossorigin="anonymous"
            async>
        </script>
        <p>Comments by <a href="https://giscus.app/">giscus</a>, use a <a href="https://github.com/">GitHub</a>
            account to comment.
        </p>
    </div>
    {% endif %}
</div>
{% endblock %}