I am trying to figure out how to pass a variable into a custom template function and so far I haven’t been able to figure out how to make it work. The idea is that I am going to have a template be passed in and I want to have it call a custom Jinja2 function. I need to pass down a variable to the custom function. This will run in a Celery job, but for the sake of this question, I have simplified the issue.
Something similar to:
import jinja2
def calling_function():
var1 = "joe"
environment = jinja2.Environment()
func_dict = {
"do_it": do_it
}
environment.globals.update(func_dict)
output = environment.from_string("{{ do_it() }}").render()
print(output)
def do_it():
return "yes: %s" % (var1)
calling_function()
I get a Name error which makes sense because it is out of scope:
NameError: name ‘var1’ is not defined. Did you mean: ‘vars’?
If I put var1 outside of the scope:
import jinja2
var1 = ""
def calling_function():
var1 = "joe"
environment = jinja2.Environment()
func_dict = {
"do_it": do_it
}
environment.globals.update(func_dict)
output = environment.from_string("{{ do_it() }}").render()
print(output)
def do_it():
return "yes: %s" % (var1)
output:
yes:
The script completes but var1 is still empty. I would like to be able to get a variable down to do_it without having to manipulate or have anything more than {{ do_it() }}. I don’t know if I need to pass the variable into the template and then pull it back out?
user25432002 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.