Django-如何使变量可用于所有模板?

我想知道如何向所有模板传递变量,而不用在 views.py 文件中的每个方法上重复相同的代码?

在下面的例子中,我想让类别(一个类别对象的数组)可用于 Web 应用程序中的所有模板。

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))
24516 次浏览

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:

  • Add custom_app to INSTALLED_APPS in settings.py (you've done it already, right?);
  • Create a context_processors.py into custom_app folder;
  • Add the following code to that new file:

    def categories_processor(request):
    categories = Category.objects.all()
    return {'categories': categories}
    
  • Add context_processors.py to TEMPLATE_CONTEXT_PROCESSORS in settings.py

    TEMPLATE_CONTEXT_PROCESSORS += ("custom_app.context_processors.categories_processor", )
    

And now you can use \{\{categories}} in all the templates :D

As of Django 1.8

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")

Or include that string directly in the OPTIONS.context_processors key in your TEMPLATES setting.