How to add a context processor from a Django app
Say I'm writing a Django app, and all the templates in the app require a certain variable.
The "classic" way to deal with this, afaik, is to write a context processor and add it to TEMPLATE_CONTEXT_PROCESSORS in the settings.py.
开发者_如何学JAVAMy question is, is this the right way to do it, considering that apps are supposed to be "independent" from the actual project using them?
In other words, when deploying that app to a new project, is there any way to avoid the project having to explicitly mess around with its settings?
Your assumption that apps can just be added in a project without touching the project's settings is not correct.
If you add an application to a project, you have to edit the settings, since you must add it in the INSTALLED_APPS
tuple.
So why not edit the context processor list?
Context processors are very useful and I wouldn't be too shy in using them, but in some situations it doesn't make sense.
This is a technique I use when I need to include something simple to all views in an app. I cannot attest that this is the 'proper' way to do things, but it works for our team:
I'll declare a global dictionary template_vars
at the top of the file. Every view would add its own variables to this dictionary and pass it to the template, and it returns template_vars
in the render_to_response
shortcut.
It looks something like this:
template_vars = {
'spam': 'eggs',
}
def gallery(request):
"""
portfolio gallery
"""
template_vars['projects'] = Projects.objects.all()
return render_to_response('portfolio/gallery.html', template_vars, context_instance=RequestContext(request))
Yeah, adding a context processor is the most recommended approach to achieve this.
精彩评论