gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:43:44 25 4
gpt4 key购买 nike

在 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 %}

关于python - 在 jinja2 中,如何两次包含相同的模板但传入不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com