我想在Jinja2模板中创建目录和尾注。如何才能完成这些任务呢?
例如,我希望有一个模板,如下所示:
{% block toc %}
{# ... the ToC goes here ... #}
{% endblock %}
{% include "some other file with content.jnj" %}
{% block endnotes %}
{# ... the endnotes go here ... #}
{% endblock %}其中some other file with 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的框架内,是否有一种模式可以适应这一点。
我最初的想法是创建一个扩展,这样就可以为章节和结尾注释创建一个块,就像- so:
{% section "One" %}
Title information goes here.
{% endsection %}
{% endnote "one" %}
<a href="#">...</a>
<script> ... </script>
{% endendnote %}然后是全局函数(在Jinja2环境中传递):
{{ table_of_contents() }}
{% include ... %}
{{ endnotes() }}然而,虽然这将适用于尾注,但我认为它需要对目录进行第二次传递。
感谢您的阅读。我将非常感谢您的想法和意见。
布赖恩
发布于 2010-08-16 18:32:39
在为每个部分定义一致的结构(即标题、正文、尾注)方面,您似乎走在了正确的道路上。将这些信息存储在常规的Python数据结构中-而不是Jinja块和/或自定义扩展-是可以接受的吗?下面是一个例子。
在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是默认的模板格式)。
https://stackoverflow.com/questions/2868066
复制相似问题