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

1.2k Views Asked by At

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.

3

There are 3 best solutions below

1
On BEST ANSWER

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

7
On

Since it should apply for all of your views the best option is to create a custom context processor. Templatetags would have the disadvantage that you have to include them everywhere you need this variable. Creating your own RequestContext as D.A. stated is overkill in my opinion.

1
On

If you want to set the variable within a template (but only if it doesn't already exist), the following should work:

{% with my_context_var=my_context_var|default:"Value you want to set it to" %}
    {# The variable is accessible within then with block #}
    {{ my_context_var }}
{% endwith %}