在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
在变量中动态设置变量content_template.html
?
使用Jinja2宏来参数化您的模板。
宏就像一个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"))
这也将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 %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句