design-patterns - 创建将内容放在不同位置的 Jinja2 宏

标签 design-patterns templates template-engine jinja2

我想在 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/

相关文章:

python - 国际化 html 模板的性能

java - 在 java web 应用程序中,我应该在哪里存储用户照片?

objective-c - 没有协议(protocol)的 iOS 委托(delegate)?

java - 数据库保存后是否真的有必要从事务中返回保存的实体?

c++ - 成员模板实例化

c++ - 将值插入以不同方式排序的两个BST中

c++ - 模板值特化

oop - 策略与桥梁模式

jquery - 使用 handlebars.js 在下拉列表中设置选定值

javascript - 避免在 underscorejs 上使用全局变量