fffred
fffred

Reputation: 697

Templating Sphinx's sidebar toctree

I am trying to make a new Sphinx template, which would create a custom toctree for the sidebar.

Using the Jinja templating language, there seems to be only one function available: toctree() which displays all the toctree at once but I need to loop through individual toctree items.

This would look like that:

{% for element in toctree_elements %}
    {{ ... display the stuff as wanted }}
{% endfor %}

Is it possible?

Upvotes: 2

Views: 785

Answers (2)

Wes Turner
Wes Turner

Reputation: 1260

fulltoc.py in sphinx-contrib/fulltoc modifies context['toc'] by running html_page_context when the html-page-context event runs.

Extension for Sphinx to make the sidebar show a full table of contents instead of just the local headings

Upvotes: 0

fffred
fffred

Reputation: 697

I finally found one trick, but it is not very satisfying.

This takes the html toctree from the function toctree() and removes all unwanted html tags. Only the URLs and titles are kept, and an array is created.

{% set theTocTree = toctree()
    | replace("</a>", "")
    | replace(" href=\"", "></a>")
    | replace("</li>", "</li>;")
    | striptags
    | replace("\">", "%") %}
{% set theTocTree = theTocTree.split(";") %}

Then, the following loops over the new toctree array to do whatever is needed.

{% for element in theTocTree %}
    {% set el = element.split("%") %}
    {% set url = el[0] | trim | safe %}
    {% set entry = el[1] | trim | safe %}
    ... here, you can use variables url and entry ...
{% endfor %}

This solution is unclean because it depends on the toctree html rendering, which might change in future Sphinx versions. Furthermore, it does not accept the characters % and ; in URLs or toctree entries.

Upvotes: 2

Related Questions