简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM