extract_toc

Hand-styled tables of content for sphinx themes.

Attention

This extension is enabled automatically when using the artisan theme.

Usage

Custom themes

You can enable this extension by adding the following to your conf.py file.

extensions = [
  "sphinx_artisan_theme.ext.extract_toc",
  ...
]

Jinja2 helpers

get_navigation()

get_navigation(*, prune, maxdepth, titles_only, includehidden)

Extracts the in-page table of contents similar to the sphinx {{toctree()}} helper but returns a list of NavigationSection instances.

Parameters:
  • prune (bool) – prune the tree to maxdeepth

  • maxdepth (int) – maximum depth to recurse the table

  • titles_only (bool) – only use top level document titles

  • includehidden (bool) – include hidden toctrees

Returns:

A list of navigation sections

Return type:

list[NavigationSection]

Example

{% macro navigation(item) %}
<li>
    <a 
      href="{{ item.url }}"
      {% if item.is_active %}class="active"{% endif %}
    >
      {{ item.title }}
    </a>
    {% if item.children %}
    <ul>
      {% for child in item.children %}
        {{ navigation(item) }}
      {% endfor %}
    </ul>
    {% endif %}
</li>
{% endmacro %}

{% for section in get_navigation(
    collapse=True,
    maxdepth=3,
    titles_only=True,
    includehidden=False
) %}
  {% if section.title %}
    <h2>{{ section.title }}
  {% endif %}
  <ul>
    {% for item in section.children %}
      {{ navigation(item) }}
    {% endfor %}
  </ul>
{% endfor %}

get_table_of_contents()

get_table_of_contents()

Extracts the in-page table of contents similar to the sphinx {{toc}} helper but returns an iterable of NavigationItem instances.

Returns:

A list of navigation items

Return type:

list[NavigationItem]

Example

{% macro navigation(item) %}
<li>
  <a 
    href="{{ item.url }}"
    {% if item.is_active %}class="active"{% endif %}
  >
    {{ item.title }}
  </a>
  {% if item.children %}
    <ul>
      {% for child in item.children %}
        {{ navigation(item) }}
      {% endfor %}
    </ul>
  {% endif %}
</li>
{% endmacro %}

<ul>
  {% for item in get_table_of_contents() %}
    {{ navigation(item) }}
  {% endfor %}
</ul>

Reference

Provides jinja2 helpers for customisable tables of contents.

class NavigationItem(title, url, children, is_active)

Navigation item.

Represents an individual link in a table of contents.

Parameters:
  • title (str) – visible title

  • url (str) – link address

  • children (list[NavigationItem]) – child navigation items

  • is_active (bool) – is the current active page

class NavigationSection(title, children)

Navigation section.

represents a section of the table of contents with optional title.

Parameters:
setup(app)

Registration callback.

Setup the extension with sphinx

Parameters:

app (Sphinx) – the sphinx application

Return type:

dict[str, Any]