Reputation: 1766
I have managed to call python functions from jinja2 by using custom filters, but I can only seem to call functions with one or more parameters. In the following I have had to pass a junk parameter in order to treat ctest as a function rather than a variable.
It also doesn't work if I just call {{ ctest() }}
.
Is there a different way to force this to be a function call or should I be using a different approach?
code:
def ctest(stuff):
return "yeah!"
template_env = jinja2.Environment (loader = jinja2.FileSystemLoader(template_file_root))
#custom filters
template_env.filters['ctest'] = ctest
template:
Working? {{ junk|ctest }}
output:
working? yeah!
Upvotes: 5
Views: 6108
Reputation: 3521
{{func()}}
renders the output.
{% call func() %}{%endcall%}
calls func()
with a caller
parameter.
In jinja there really seems to be no straightforward way to call a python function in the template without rendering it or other template side effects. The workaround I came up with is:
{% if func() %}{% endif %}
Upvotes: 0
Reputation: 1766
Summarizing the comments into an answer:
The ability to call functions by adding it to filters isn't really the correct way of going about this since (as Wooble pointed out) I'm not looking to filter anything.
Instead the function just needs to be added to the template_env.globals:
template_globals.filters['ctest'] = ctest
Upvotes: 1
Reputation: 90007
Well, they're filters, so they expect to be filtering something. If the motivation is that you want to function to be callable from outside a template without passing any arguments, change the signature to:
def ctest(*args):
and then just ignore the arguments; it will work if it's passed no arguments or any number of them.
Upvotes: 1