Access global attributes from inside a macro in Jinja2

I use macros extensively in Jinja2 and find them very dry; but one thing bothers me: how to access global materials from macros? That would be very neat if I could somehow access url_for () from a macro.

+7
source share
1 answer

You can make any available available in the Jinja environment:

jinja_env = Environment(...) jinja_env.globals['url_for'] = url_for 

For example, this u'foobar 'output in the shell:

 from jinja2 import Environment env = Environment() env.globals['foo'] = lambda: "foobar" env.from_string('{% macro bar() %}{{ foo() }}{% endmacro %}{{ bar() }}').render() 
+8
source

All Articles