What is context in Jinja2?

Viewed 1745

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)

file.j2

{{ context.test1 }} 

I'm learning Jinja2 and I understood that context are the variables that are passed to Template but when I execute the above code, i get the below error

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

I've read the docs and I couldn't understand it completely. Can you please explain what is context and how it is used to access the variables?

1 Answers

Context contains the dynamic content that you want to inject in your template when it is being rendered.

In your example, the file file.j2 must have the following content:

{{ test1 }} 

As context is not a variable but the collection of all variables you pass to the template. test1 and test2 are part of the context.

Related