Closed clarkwang closed 3 months ago
@clarkwang The error occurs because globals
is being incorrectly passed to get_template
. The correct way to add globals
to the Jinja2 environment is to set them on the Environment
object itself.
#!/usr/bin/env python3
import jinja2 as j2
import os
import sys
print(f'jinja2 version: {j2.__version__}')
# Set up Jinja2 environment and add the global function
env = j2.Environment(loader=j2.FileSystemLoader('.'))
env.globals['ENV'] = os.getenv
# Load the template specified by the first command line argument
tmpl = env.get_template(sys.argv[1])
# Render the template
print(tmpl.render())
get_env_variable
Function: You use the os.getenv
directly without wrapping it in another function. This makes the template code {% set var1 = ENV('HOME') %}
work correctly, as ENV
now maps directly to os.getenv
.env.globals['ENV'] = os.getenv
, the environment variable access function is globally available in all templates rendered by this environment.@j7an adding globals to a template is supported: https://jinja.palletsprojects.com/en/3.1.x/api/#the-global-namespace. That said, you're correct that they're not setting the globals in the correct place. In their example, they set the globals on file1
, but it's common
that needs access. They should either set the globals on common
, or on the environment as you showed.
I've come up with the following minimal repro steps.
Python script:
Data files:
To repro the issue:
As we can see,
python3 test.py file2
works butpython3 test.py file1
fails.