如何使用同一Python脚本中的字符串超级块扩展jinja2模板

2024-04-30 01:46:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白如何用同一个Python脚本中的字符串超级块扩展jinja2模板

示例代码

from jinja2 import Template

hello = """
hello
"""

world = """
{% extends 'hello' %}
world
"""

j2_template = Template(world)
print(j2_template.render())

显然,我想打印“hello world”,但我出错了

TypeError: no loader for this environment specified

我检查了Jinja2加载程序文档,但找不到如何将字符串引用为超级块。 如果您能帮助解决此问题,我们将不胜感激


Tags: 字符串代码fromimport脚本模板jinja2示例
1条回答
网友
1楼 · 发布于 2024-04-30 01:46:19

Jinja不知道hello模板在哪里。您需要先删除{% extends 'hello' %}并呈现hello,然后将其作为变量插入字符串模板中

world = Template("""{} world""".format(Template(hello).render()))
print(world.render())

相关问题 更多 >