开发者

Accessing global attributes from inside a macro in Jinja2

开发者 https://www.devze.com 2023-02-11 12:52 出处:网络
I\'ve been using macros in Jinja2 extensively and find them very DR开发者_运维百科Y-ish; but there is one thing bothering me: how to access global stuff from macros? It would be really neat if I could

I've been using macros in Jinja2 extensively and find them very DR开发者_运维百科Y-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.


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() 
0

精彩评论

暂无评论...
验证码 换一张
取 消