jinja_code.py
import jinja2
env=jinja2.Environment(loader=FileSystemLoader(searchpath="./"))
template=env.get_template('file.j2')
render_template=template.render(test1="TEST1",test2="TEST2")
print(render_template)
文件.j2
{{ context.test1 }}
我正在学习 Jinja2,我理解上下文是传递给模板的变量,但是当我执行上面的代码时,我收到以下错误
jinja2.exceptions.undefinederror: 'context' is not defined
我已经阅读了文档,但我无法完全理解它。您能解释一下什么是上下文以及如何使用它来访问变量吗?
上下文包含您要在渲染模板时注入模板的动态内容。
在您的示例中,文件 file.j2 必须具有以下内容:
{{ test1 }}
上下文不是变量,而是传递给模板的所有变量的集合。 test1 和 test2 是上下文的一部分。
以下是render_template的签名:
def render_template(
template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],
**context: t.Any
) -> str
context
参数前面有两个星号,表示可以传递任意数量的参数。因此,语句 template.render(test1="TEST1",test2="TEST2")
将导致字典通过 context
参数,如下所示:{'test1': 'TEST1', 'test2': 'TEST2'}
。
Jinja 会在幕后自动解压
context
(您不必这样做,因为它已经为您完成了):
test1 = context['test1']
test2 = context['test2']
然后您可以直接使用
test1
:
{{ test1 }}