简体   繁体   English

django上下文处理器

[英]django context processor

I have a bunch of variables that need to be available to the view for all templates. 我有一堆变量需要可供所有模板的视图使用。 It seems the best choice would be a context processor. 似乎最好的选择是上下文处理器。

The documentation says: 文件说:

A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. 上下文处理器有一个非常简单的接口:它只是一个Python函数,它接受一个参数,一个HttpRequest对象,并返回一个被添加到模板上下文的字典。 Each context processor must return a dictionary. 每个上下文处理器必须返回一个字典

If I need to do more advanced lookups, can I define other functions? 如果我需要进行更高级的查找,我可以定义其他功能吗? Do the functions need to be in a class? 这些功能需要在课堂上吗? I was thinking of creating a file named context_processors.py in my app folder. 我想在我的app文件夹中创建一个名为context_processors.py文件。

You can define other functions, and the functions don't need to be in a class. 您可以定义其他函数,并且函数不需要在类中。

Typically people put their context processors into a context_processors.py like you're thinking of as functions, and then name them all in settings.TEMPLATE_CONTEXT_PROCESSORS . 通常人们将他们的上下文处理器放入context_processors.py就像你想象的那样是函数,然后在settings.TEMPLATE_CONTEXT_PROCESSORS中将它们全部命名。

For example, here's an app that has the context_processors.py inside it: django-seo . 例如,这是一个内置了context_processors.py的应用程序: django-seo

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

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