Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 金贾2中的语境是什么?_Python_Templates_Django Templates_Jinja2 - Fatal编程技术网

Python 金贾2中的语境是什么?

Python 金贾2中的语境是什么?,python,templates,django-templates,jinja2,Python,Templates,Django Templates,Jinja2,jinja_代码.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) file.j2

jinja_代码.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)
file.j2

{{ context.test1 }} 
我正在学习Jinja2,我知道上下文是传递给模板的变量,但是当我执行上面的代码时,我得到了下面的错误

jinja2.exceptions.undefinederror: 'context' is not defined

我读过文件,不能完全理解。您能否解释什么是上下文以及如何使用上下文访问变量?

上下文包含在呈现模板时要注入到模板中的动态内容

在您的示例中,文件file.j2必须包含以下内容:

{{ test1 }} 

因为上下文不是一个变量,而是传递给模板的所有变量的集合test1test2是上下文的一部分。

尝试
{{test1}}
不使用上下文是的,我知道这是可行的。但是我看到一段代码,其中用户只编写了{%set name=context.FirstName%}。所以我很困惑这个上下文是从哪里加载的?但是我看到了一段代码,其中用户只编写了{%set name=context.FirstName%}。那么,您能解释一下如何处理它吗?如果您需要使用{{context.test1},您需要以如下方式将它作为dict传递给模板:render_template=template.render(context={“test1”:“test1”,“test2”:“test2”})