Python 在jinja2中,如何包含相同的模板两次,但传递不同的变量
在jinja2中,我尝试多次使用该模板动态创建html文档。 我的python脚本如下所示:Python 在jinja2中,如何包含相同的模板两次,但传递不同的变量,python,jinja2,Python,Jinja2,在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 =
# 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>
我的基本模板如下所示:
# 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\u template.html
关联的值动态设置content
变量?用于参数化模板
宏类似于Python函数;您可以定义一个模板片段,以及它所使用的参数,然后可以像调用函数一样调用宏
我将把宏放在一个宏模板中,然后将该模板放在基础模板中。将要使用的宏的名称传入基础模板:
# content and macro name
content1 = ("Hello World", 'content_template')
content2 = ("Foo bar", 'content_template')
base_template.render(include_these=[content1, content2]).encode("utf-8"))
这也会将宏
上下文过滤器添加到环境中
在你的base_template.html
中有:
{%import“macros.html”作为宏%}
文件
{%对于内容,宏名称在include_this%}
{%macros[macroname](内容)%}
{%endfor%}
以及macros.html
模板:
# 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 content\模板(content)-%}
{{content}}
{%-endmacro%}