简体   繁体   English

@context_processor如何影响模板变量?

[英]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. 然后,他们使用session['nonce'] = XXXXX并在模板中使用{{ nonce }}

If I define a var in a context processor, do I know all of its attributes? 如果在上下文处理器中定义var,我是否知道其所有属性? Is {{ nonce }} the same as the session value? {{ nonce }}是否与会话值相同?

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 ? 我的结论是, session变量被传递给所有的模板,但目前还不清楚,如果它的属性也知道,如果是的话是不是应该被用来作为session.nonce代替nonce

Flask passes the session to the template context by default. 瓶传递session到系统默认的模板背景。 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. 您发布的背景处理器从会话的所有项目,并直接在模板背景使他们,所以他们没有通过访问session变种。

{{ 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. 最终,您发布的上下文处理器几乎没有用,但是在某些情况下可能会很方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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