Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing global attributes from inside a macro in Jinja2

Tags:

python

jinja2

I've been using macros in Jinja2 extensively and find them very DRY-ish; but there is one thing bothering me: how to access global stuff from macros? It would be really neat if I could somehow access url_for() natively from a macro.

like image 824
Jure V. Avatar asked Feb 17 '11 20:02

Jure V.


People also ask

What is Jinja2 macro?

Macros are similar to functions in many programming languages. We use them to encapsulate logic used to perform repeatable actions. Macros can take arguments or be used without them. Inside of macros we can use any of the Jinja features and constructs. Result of running macro is some text.


1 Answers

You can make any callable available in the Jinja environment:

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

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

from jinja2 import Environment
env = Environment()
env.globals['foo'] = lambda: "foobar"
env.from_string('{% macro bar() %}{{ foo() }}{% endmacro %}{{ bar() }}').render() 
like image 102
jd. Avatar answered Oct 07 '22 22:10

jd.