Search code examples
djangodjango-templatesdjango-context

How to inject template context variable only if it doesn't exist


I have a base_template.html that uses a context variable my_context_var. All of my other templates extends this base template. Can you help me answer one of these questions? (They are just different ways to look at the same underlying problem)

  1. How can I make my_context_var available to all the derived templates but allow a way to override my_context_var for specific views.

  2. How can I inject my_context_var into the template context only if that variable is not already there.

Essentially, I'm looking for a setdefaults() functionality for context variables. If it helps, my_context_var is basically a blank search form that is available in most pages of my site. I need to override it for one page that displays both the form and the result. The current problem is that I keep getting the blank form even for that result page.


Solution

  • You have a couple options:

    You can create your own RequestContext and include all the variables you want through your site: Documentation

    Or you can create template tags and access them in any template: Documentation