Search code examples
pythonjinja2

Can jinja2 templates access (and modify) global python script variables?


I would like to create a certain text file structure using python and jinja2. (not HTML). The files are static, and built of several segments, each segment is created by a different jinja template.

Each of these segments that come in random order must be numbered sequentially.

In principle:

Segment A  (no 1)
---
My Segment B (no 2)
---
Another Segment C (no 3)

I keep track of the current number using a variable in python.

I can of course transfer this variable to each template, like this.

outfile=[]   # array for output
# get some objects...
for i in range(1,5):   # example to test
    t=myTemplate.render(nr=i, mystring=f"This is template nr {i}")
    outfile.append(t)

For clarity and simplicity, I would like to avoid having to transfer the global/s (there may be more) to every template render call.

Is it Jinja2 global namespaces I need to look for ?


Solution

  • You can modify Jinja2 environment to define global variables that can be later accessed by any template within that environment like so: (Example made with Flask app - other runtimes might mean different way of accessing the env)

    app.jinja_env.globals['varName'] = 'variableValue'
    

    this lets you access the variable just like it would be passed into render_template

    return render_template("template.html", varName = 'variableValue')