Auto number Headings & TOC in Hugo Pages Auto number Headings & TOC in Hugo Pages

Page content

In this tutorial, we’ll learn how to generate auto-numbering for headings, subheadings, and TOC in Hugo Pages.

Overview

When you generate a website using Hugo static site generator, It doesn’t provide any out of the box auto-numbering support for headings, subheadings, and TOC in Hugo Pages.

This blog website is also generated using Hugo and with few changes, we’re able to add auto-numbering support to our Hugo Pages.

If you’re still not clear what is auto-numbering all about then look at the auto incrementing numbers before the headings, subheadings and TOC in this post i.e. 1, 2, 2.1, 2.2, 2.3 etc.

1. Overview
2. Auto-numbering Pages
    2.1. Add “autonumbering” property in front-matter
    2.2. Add CSS Class to single.html
    2.3. Add CSS Styles to style.css

Let’s discuss how to enable this feature.

Auto-numbering Pages

Follow these three steps to enable auto-numbering feature in your Hugo website:

Add “autonumbering” property in front-matter

We’re going to add a custom property autonumbering in the front-matter of our Hugo pages.

We can enable or disable auto-numbering for a specific page using this property. If autonumbering: true, means it is enabled otherwise disabled.

blog-page.md
---

...

autonumbering: true
---


Add CSS Class to single.html

You need to add autonumbering CSS class on the article element based on autonumbering property is enabled or disabled.

single.html
{{ define "main" }}
<main>
  <article class="post" {{- if .Param "autonumbering" }} autonumbering {{- end }}>
    <header>
     ...
    </header>	
     ...
    <footer>
     ...
    </footer>
  </article>
</main>
{{ end }}

If autonumbering is enabled on any post. It will look like this:

<main>
  <article class = "post autonumbering" ></article>
</main>

If autonumbering is disabled on any post. It will look like this:

<main>
  <article class = "post" ></article>
</main>


Add CSS Styles to style.css

In the end, Add the following CSS Styles snippet in the CSS files you would be using in your project:

styles.css
/* Auto Numbering */
body {counter-reset: h2}
h2 {counter-reset: h3}
h3 {counter-reset: h4}
h4 {counter-reset: h5}

article[autonumbering] h2:before {counter-increment: h2; content: counter(h2) ". "}
article[autonumbering] h3:before {counter-increment: h3; content: counter(h2) "." counter(h3) ". "}
article[autonumbering] h4:before {counter-increment: h4; content: counter(h2) "." counter(h3) "." counter(h4) ". "}

article[autonumbering] .toc__menu ul { counter-reset: item }
article[autonumbering] .toc__menu li a:before { content: counters(item, ".") ". "; counter-increment: item }

That’s it. You should be able to use autonumbering feature in your hugo pages now.