Django - 如何使变量可用于所有模板? [英] Django - How to make a variable available to all templates?
问题描述
我想知道如何将变量传递给我的所有模板,而不在我的 views.py 文件中的每个方法上重复相同的代码?
I would like to know how to pass a variable to all my templates, without repeating the same code on every method in my views.py file?
在下面的示例中,我想让类别(类别对象的数组)可用于网络应用程序中的所有模板.
In the example below I would like to make categories (an array of category objects) available to all templates in the web app.
Eg: I would like to avoid writing 'categories':categories on every method. Is it possible?
一种查看方法
def front_page(request):
categories = Category.objects.all()
if is_logged_in(request) is False:
return render_to_response('users/signup.html', {'is_logged_in': is_logged_in(request), 'categories':categories}, context_instance=RequestContext(request))
else:
return render_to_response('users/front_page.html', {'is_logged_in': is_logged_in(request), 'categories':categories},context_instance=RequestContext(request))
另一种查看方法
def another_view_method(request):
categories = Category.objects.all()
return render_to_response('eg/front_page.html', {'is_logged_in': is_logged_in(request), 'categories':categories},context_instance=RequestContext(request))
推荐答案
你想要的是一个上下文处理器,而且很容易创建一个.假设您有一个名为 custom_app
的应用,请按照以下步骤操作:
What you want is a context processor, and it's very easy to create one. Assuming you have an app named custom_app
, follow the next steps:
- 将
custom_app
添加到settings.py
中的INSTALLED_APPS
(您已经完成了,对吧?); - 在
custom_app
文件夹中创建一个context_processors.py
; 将以下代码添加到该新文件中:
- Add
custom_app
toINSTALLED_APPS
insettings.py
(you've done it already, right?); - Create a
context_processors.py
intocustom_app
folder; Add the following code to that new file:
def categories_processor(request):
categories = Category.objects.all()
return {'categories': categories}
将 context_processors.py
添加到 settings.py
TEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", )
现在你可以在所有模板中使用 {{categories}}
:D
And now you can use {{categories}}
in all the templates :D
从 Django 1.8 开始
要添加TEMPLATE_CONTEXT_PROCESSORS
,您必须在设置中添加下一个代码:
To add a TEMPLATE_CONTEXT_PROCESSORS
, in the settings you must add the next code:
TEMPLATES[0]['OPTIONS']['context_processors'].append("custom_app.context_processors.categories_processor")
或者将该字符串直接包含在 TEMPLATES
设置中的 OPTIONS.context_processors
键中.
Or include that string directly in the OPTIONS.context_processors
key in your TEMPLATES
setting.
这篇关于Django - 如何使变量可用于所有模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!