brad
brad

Reputation: 501

How does @context_processor effect template variables?

I found the following code:

@app.context_processor
def inject_user():
    if authed():
        return dict(session)
    return dict()

Then they use session['nonce'] = XXXXX and use the {{ nonce }} in a template.

If I define a var in a context processor, do I know all of its attributes? Is {{ nonce }} the same as the session value?

I concluded that the session var is passed to all the templates, but it's not clear if its attributes are also known, and if so isn't it supposed to be used as session.nonce instead of nonce?

Upvotes: 0

Views: 178

Answers (1)

davidism
davidism

Reputation: 127210

Flask passes the session to the template context by default. This can be used just like in your view code, it is a dictionary.

{{ session['nonce'] }}
or {{ session.nonce }}

The context processor your posted takes all the items from the session and puts them directly in the template context, so they don't have to be accessed through the session var.

{{ nonce }} comes from session through the context processor

Ultimately, the context processor you posted is pretty useless, but it could be convenient in some cases.

Upvotes: 2

Related Questions