在 jinja2 中,如何两次包含相同的模板但传入不同的变量

In jinja2, how to include the same template twice but pass in different variables

在 jinja2 中,我试图多次使用模板动态创建 html 文档。 我的 python 脚本如下所示:

# In my python script
env = Environment()
env.loader = FileSystemLoader('.')
base_template = env.get_template('base_template.html')

# each has the actual content and its associated template 
content1 = ("Hello World", 'content_template.html') 
content2 = ("Foo bar", 'content_template.html')


html_to_present = [content1[1], content2[1]]

# and render. I know this is wrong 
# as I am not passing the actual content, 
# but this is the part I am struggling with. More below
base_template.render(include_these=html_to_present, ).encode("utf-8"))

我的基本模板如下所示:

#################
# base_template.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {% for include_this in include_these %}
    {% include include_this %}
    {% endfor %}    
</body>
</html>

content_template.html看起来像这样

# content_template.html
<div>
    {{ content }}
</div>

现在我的问题是,如何根据关联的值在 content_template.html 中动态设置 content 变量?

使用 Jinja2 macros 参数化您的模板。

宏就像一个Python函数;你定义一个模板片段,加上它需要的参数,然后你可以像调用函数一样调用宏。

我会将这些宏放在一个宏模板中,然后 import 将该模板放入您的基本模板中。将要使用的宏的名称传递给基本模板:

# content and macro name
content1 = ("Hello World", 'content_template') 
content2 = ("Foo bar", 'content_template')

base_template.render(include_these=[content1, content2]).encode("utf-8"))

这也会将 macro 上下文过滤器添加到环境中。

并且在您的 base_template.html 中有:

{% import "macros.html" as macros %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {% for content, macroname in include_these %}
    {% macros[macroname](content) %}
    {% endfor %}
</body>
</html>

macros.html 模板:

{% macro content_template(content) -%}
<div>
    {{ content }}
</div>
{%- endmacro %}