首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >创建可将内容放在不同位置的Jinja2宏

创建可将内容放在不同位置的Jinja2宏
EN

Stack Overflow用户
提问于 2010-05-20 01:58:15
回答 1查看 1.8K关注 0票数 3

我想在Jinja2模板中创建目录和尾注。如何才能完成这些任务呢?

例如,我希望有一个模板,如下所示:

代码语言:javascript
运行
复制
 {% 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的内容如下:

代码语言:javascript
运行
复制
{% 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:

代码语言:javascript
运行
复制
{% section "One" %}
Title information goes here.
{% endsection %}

{% endnote "one" %}
<a href="#">...</a>
<script> ... </script>
{% endendnote %}

然后是全局函数(在Jinja2环境中传递):

代码语言:javascript
运行
复制
{{ table_of_contents() }}

{% include ... %}

{{ endnotes() }}

然而,虽然这将适用于尾注,但我认为它需要对目录进行第二次传递。

感谢您的阅读。我将非常感谢您的想法和意见。

布赖恩

EN

回答 1

Stack Overflow用户

发布于 2010-08-16 18:32:39

在为每个部分定义一致的结构(即标题、正文、尾注)方面,您似乎走在了正确的道路上。将这些信息存储在常规的Python数据结构中-而不是Jinja块和/或自定义扩展-是可以接受的吗?下面是一个例子。

content.jnj

代码语言:javascript
运行
复制
{% 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

代码语言:javascript
运行
复制
{% 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是默认的模板格式)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2868066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档