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.
文档说:
上下文处理器的界面非常简单:它只是一个Python该函数接受一个参数,一个HttpRequest对象并返回一个添加到模板上下文的字典.每个上下文处理器必须返回字典.
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. Each context processor must return a dictionary.
如果需要执行更多高级查找,可以定义其他功能吗?这些功能需要在一个类中吗?我当时正在考虑在我的应用文件夹中创建一个名为 context_processors.py
的文件.
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.
推荐答案
您可以定义其他函数,并且这些函数不必在类中.
You can define other functions, and the functions don't need to be in a class.
通常,人们将上下文处理器放入您想像为函数的 context_processors.py
中,然后在 settings.TEMPLATE_CONTEXT_PROCESSORS
中将它们全部命名.
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
的应用程序:django-seo .
For example, here's an app that has the context_processors.py
inside it: django-seo.
这篇关于Django上下文处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!