Depending on the project you are working on, you might want to access one or more template variables across all your templates like the User object. If you are making news or blog project, one example would be navigation bar item, say a category list.
You might be tempted to pass the category list from your views or create a template tag for that; but that just violate the Django’s DRY principle. So the best way would be through custom context processor. Writing your own is actually very easy.
1. Writing the context processor function.
You can put this function anywhere in your project. My preference is to place this code inside a context_processors.py file under the related app.
|1 2 3 4 5 6 7||
Note: Each context processor must return a dictionary and takes only one arguement, HttpRequest object.
2. Point it to your TEMPLATE_CONTEXT_PROCESSORS in your settings.py file.
|1 2 3 4 5 6 7 8 9||
Now categories is available for use in all your templates.