我想在 Jinja2 模板中创建目录和尾注。如何完成这些任务?
比如我想要一个模板如下:
{% block toc %}
{# ... the ToC goes here ... #}
{% endblock %}
{% include "some other file with content.jnj" %}
{% block endnotes %}
{# ... the endnotes go here ... #}
{% endblock %}
一些带有 content.jnj 的其他文件
包含如下内容:
{% section "One" %}
Title information for Section One (may be quite long); goes in Table of Contents
...
Content of section One
{% section "Two" %}
Title information of Section Two (also may be quite long)
<a href="#" id="en1">EndNote 1</a>
<script type="text/javsacript">...(may be reasonably long)
</script> {# ... Everything up to here is included in the EndNote #}
我说“可能相当长/相当长”的意思是说它不能合理地作为宏或全局函数的参数放在引号中。
我想知道在 Jinja2 的框架内是否有一种模式可以适应这种情况。
我最初的想法是创建一个扩展,这样就可以有一个 block 用于章节和尾注,就像这样:
{% section "One" %}
Title information goes here.
{% endsection %}
{% endnote "one" %}
<a href="#">...</a>
<script> ... </script>
{% endendnote %}
然后有全局函数(在 Jinja2 环境中传递):
{{ table_of_contents() }}
{% include ... %}
{{ endnotes() }}
但是,虽然这对尾注有效,但我认为它需要对目录进行第二次传递。
感谢阅读。非常感谢您的想法和意见。
布莱恩
最佳答案
似乎您在为每个部分(即标题、正文、尾注)定义一致的结构方面正朝着正确的方向前进。将此信息存储在常规 Python 数据结构中——而不是 Jinja block 和/或自定义扩展中——是否可以接受?示例如下。
在 content.jnj
中:
{% set sections = [] %}
{% do sections.append({
'title': 'Section One title',
'body':
"""
Section one main body text...
""",
'endnotes':
"""
<a href='#'>...</a>
<script> ... </script>
""",
})
%}
{# append more sections #}
在template.jnj
中:
{% from 'content.jnj' import sections as sections %}
{# table of contents #}
{% for section in sections %}
{{ loop.index }}. {{ section['title'] }}
{% endfor %}
{# body #}
{% for section in sections %}
{{ section['title'] }}
{{ section['body'] }}
{% endfor %}
{# endnotes #}
{% for section in sections %}
{{ loop.index }}. {{ section['endnotes'] }}
{% endfor %}
请注意,content.jnj
需要启用 Jinja2 do
扩展(例如 env = jinja2.Environment(extensions=['jinja2.ext.do '])
.)
对于您的目的来说,这可能有点矫枉过正,但另一种选择是以标记语言存储内容,例如 reStructuredText,并将表示层设计为 Sphinx主题(Jinja2 是默认的模板格式)。
关于design-patterns - 创建将内容放在不同位置的 Jinja2 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868066/