Vitalii Ponomar
Vitalii Ponomar

Reputation: 10946

get_template_attribute() - how to inject template globals

In flask we can render jinja2 macro from python view,

from flask import get_template_attribute

macro = get_template_attribute(template_name, macro_name)
# macro uses global variable `global_key` 
html = macro()

but there is some problem:

@app.context_processor
def inject_global_template_context():
    return dict(global_key=global_value)

doesn't work... (But it works if you render whole template).

So, how to define such global context?

Thanks in advance!!!

Upvotes: 0

Views: 917

Answers (2)

mckelvin
mckelvin

Reputation: 4068

Instead of using get_template_attribute (where global variables are not injected), you can use

from flask import current_app

tmpl = current_app.jinja_env.get_template(template_name)
mod = tmpl.make_module({'global_key': global_value})  # global variables are injected manually
getattr(mod, macro_name)()

credits: https://python5.com/q/txwccsgf

Upvotes: 1

Vitalii Ponomar
Vitalii Ponomar

Reputation: 10946

For now I've found one decision. Such as @app.context_processor decorator doesn't work, I inject custom globals to templates in other way:

app.jinja_env.globals.update(global_key1=global_value1,
                             global_key2=global_value2,
                             global_key3=global_value3)

Maybe this is not the best way to solve my problem, but it works fine for now :)

Upvotes: 1

Related Questions