summaryrefslogtreecommitdiff
path: root/docs/modules/api/pages/generate-html-toc.adoc
blob: 7af1b72472611dd4c6c1e2a0f4c41a22b63ba8e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
= 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.

== Usage

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:

[,ruby]
----
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:

[.output,html]
----
<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>
</ul>
</li>
<li><a href="#_section_c">Section C</a></li>
</ul>
----

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

[,ruby]
----
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.

[,ruby]
----
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:

[,ruby]
----
= converter.convert document, 'outline'
----

== Options

The `convert_outline` method accepts the following options:

sectnumlevels:: the number of section levels to number (defaults to the value of the `sectnumlevels` attribute.
toclevels:: 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:

[,ruby]
----
html_toc = document.converter.convert_outline document, toclevels: 1
----