Generate an HTML TOC

Asciidoctor’s HTML5 converter has a built-in method for generating an HTML TOC. This TOC generator can also be used as a general purpose API. This logic is available via the convert_outline method (which is the convert method for the outline node) on the HTML5 converter.


The convert_outline method accepts a Document object and an optional Hash of options and it returns HTML. It can be resolved and invoked as a general purpose method using the following snippet of code:

document = Asciidoctor.load_file 'document-with-sections.adoc', safe: :safe
html_toc = (Asciidoctor::Converter.create 'html5').convert_outline document
puts html_toc

Here’s an example of what this method produces:

<ul class="sectlevel1">
<li><a href="#_section_a">Section A</a></li>
<li><a href="#_section_b">Section B</a>
<ul class="sectlevel2">
<li><a href="#_subsection">Subsection</a></li>
<li><a href="#_section_c">Section C</a></li>

You can also access the convert_outline method on the converter instance by way of the Document API:

document = Asciidoctor.load_file 'document-with-sections.adoc', safe: :safe
html_toc = document.converter.convert_outline document

If you’re using a composite converter, you can use the generic convert method to ensure the call is run through the converter chain. To do so, invoke the convert method and pass in the Document object and the node name outline. This, in turn, will call convert_outline on the converter in the chain that responds to this method.

document = Asciidoctor.load_file 'document-with-sections.adoc', safe: :safe
html_doc = document.converter.convert document, 'outline'

You can also use this method inside any converter template (e.g., Slim, Haml, or ERB) to generate and embed a TOC:

= converter.convert document, 'outline'


The convert_outline method accepts the following options:


the number of section levels to number (defaults to the value of the sectnumlevels attribute.


the depth of the TOC (defaults to the value of the toclevels attribute)

Here’s an example of how you can generate an HTML TOC with the depth limited to 1 for the previously loaded document:

html_toc = document.converter.convert_outline document, toclevels: 1