Including a table of contents

1. Introduction

When a page has more than a few sections it is often useful to include a table of contents at the beginning of the page. The table of contents is a list of links to the sections contained in the page itself. Its purpose is to give the reader an overview of the page contents, and a quick way to jump to a specific section of the page.

The support for tables of contents in Yawg comes directly from Asciidoctor. You can read all about it in the Asciidoctor documentation. The following sections give just some additional information on how in practice a table of contents is included in a page.

2. Including a table of contents

To have a table of contents in your page you just have to define the AsciiDoc toc attribute in the document header. For instance, in the case of this page you are just reading the document header has the following contents:

= Including a table of contents
:toc:
:sectnums:

In the example above the sectnums AsciiDoc attribute is also included. The sectnums attribute turns on numbering for sections. We like having numbered sections when also showing a table of contents, although it certainly is a matter of personal taste.

3. Styling the table of contents

The table of contents is just a piece of HTML that is automatically included in the final page HTML content by the Asciidoctor engine. You will need to take care of styling that piece of HTML such that it matches the look and feel you want for your site.

The first thing you need to be aware is the structure of the piece of HTML corresponding to the table of contents block. Below you can see an example of the HTML generated by Asciidoctor. This actually corresponds to the table of contents in this page itself.

<div id="toc" class="toc">
  <div id="toctitle">Table of Contents</div>
  <ul class="sectlevel1">
    <li><a href="#_introduction">Introduction</a></li>
    <li><a href="#_including_a_table_of_contents">Including a table of contents</a></li>
    <li><a href="#_styling_the_table_of_contents">Styling the table of contents</a></li>
  </ul>
</div>

To style the table of contents you will just need to define the appropriate CSS styles to apply to that piece of HTML. You can define your CSS styles in a CSS file contained in your assets directory. And you should include your CSS file in the HTML header of your template file.

As an example you can see below the CSS styles that are being used in this page itself. The colors and spacings were chosen to closely match the Bootstrap style used by this site.

.toc {
    border: 0.1em solid #ccc;
    border-radius: 0.4em;
    padding: 1em 2em;
    display: inline-block;
}
.toc > div {
    font-weight: bold;
    margin-bottom: 0.5em;
}
.toc ul {
    list-style-position: inside;
    list-style-type: none;
    margin: 0;
    padding: 0 0 0 1em;
    text-indent: -1em;
}
.toc li {
    white-space: nowrap;
}