在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>
现在我的问题是如何根据与{1}}相关联的值在content
中动态设置content_template.html
变量?
答案 0 :(得分:4)
使用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 %}