Posted by José Lopes
I needed to use a constant that I defined on my project settings on several templates. I wanted to be able to use it like:
{{ MY_CONSTANT_NAME }}
I started by passing it on each view context but then, remembering the DRY principle, I made use of the TEMPLATE_CONTEXT_PROCESSORS to make it available anywhere on the project templates.
This post will show you how to create your own template context or, using the correct name, Custom context processors as its mentioned in the Django's documentation.
To help understanding let's use an example:
We have a text that we want to truncate by
a certain number of words, number that should be the same on several pages of the project.
We create the constant WORD_TRUNCATE on the project settings, so we can easily control the number of words to truncate (just one place to modify if necessary).
Then we create the our_template_tags.py file anywhere on our project. I use a utils directory to store these kind of files (don't forget to have a __init__.py file).
It should contain something like:
from django.conf import settings
def word_truncate(context):
return {'WORD_TRUNCATE': settings.WORD_TRUNCATE}
The return is always a dictionary, where we may have several values in it. It's quite powerful!
Now we add the context processor to our settings.py file:
TEMPLATE_CONTEXT_PROCESSORS = ('OUR_PROJECT.utils.our_template_tags.word_truncate')
We may of course add as many as necessary.
In order that this works the concerned view should have a RequestContext, like:
from django.template import RequestContext
from django.shortcuts import render_to_response
def our_view(request):
...
context = { 'TEXT_BLOCK': SOME_MODEL_DATA }
return render_to_response(
'OUR_TEMPLATE.html',
context,
context_instance = RequestContext(request))
Now we're set to go!
On OUR_TEMPLATE.html we can combine the context we have defined on the view with our custom template context:
{{ TEXT_BLOCK|truncatewords:WORD_TRUNCATE }}