我正在尝试制作一个新的 Sphinx 模板,它将为侧边栏创建一个自定义目录树。
使用 Jinja 模板语言,似乎只有一个可用函数:toctree()
,它一次显示所有 toctree,但我需要循环遍历各个 toctree 项。
这看起来像这样:
{% for element in toctree_elements %}
{{ ... display the stuff as wanted }}
{% endfor %}
可能吗?
最佳答案
我终于找到了一个窍门,但不是很令人满意。
这从函数 toctree()
中获取 html toctree 并删除所有不需要的 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 或目录树条目中的字符 %
和 ;
。
关于jinja2 - 模板化 Sphinx 的侧边栏目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31748047/