【问题标题】:Templating Sphinx's sidebar toctree模板化 Sphinx 的侧边栏目录树
【发布时间】:2015-07-31 13:59:17
【问题描述】:
我正在尝试制作一个新的 Sphinx 模板,它将为侧边栏创建一个自定义目录树。
使用 Jinja 模板语言,似乎只有一个功能可用:toctree() 一次显示所有目录树,但我需要遍历各个目录树项。
看起来像这样:
{% for element in toctree_elements %}
{{ ... display the stuff as wanted }}
{% endfor %}
有可能吗?
【问题讨论】:
标签:
jinja2
python-sphinx
sidebar
navigationbar
toctree
【解决方案1】:
我终于找到了一个窍门,但不是很满意。
这会从函数 toctree() 中获取 html 目录树,并删除所有不需要的 html 标签。只保留 URL 和标题,并创建一个数组。
{% set theTocTree = toctree()
| replace("</a>", "")
| replace(" href=\"", "></a>")
| replace("</li>", "</li>;")
| striptags
| replace("\">", "%") %}
{% set theTocTree = theTocTree.split(";") %}
然后,以下循环遍历新的 toctree 数组以执行任何需要的操作。
{% 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 %}
这个解决方案是不干净的,因为它依赖于 toctree html 渲染,这可能会在未来的 Sphinx 版本中发生变化。此外,它不接受 URL 或目录树条目中的字符 % 和 ;。