Pass value from one Django template to other

I want to build a Django template hierarchy like so:

  root.html
  |_ root-dashboard.html
  |_ root-regular.html

root.html shall have an if statement:

{% if style == "dashboard" %}
  {# render some elements in a certain way #}
{% else %}
  {# render those elements in a different way #}
{% endif %}

And root-dashboard.html and root-regular.html should individually extend root.html by setting style:

# root-dashboard.html
{% extend 'root.html' with style='dashboard'%}

# root-regular.html
{% extend 'root.html' with style='regular'%}

(with above is not an actual valid syntax, its just something similar I want)

And a view can use either root-dashboard.html or root-regular.html to show the content in one style or the other.

How do I achieve this without the view having to set the style context?

Define a {% block … %} template tag [Django-doc] instead.

In root.html, you don't use an if, but:

{% block render_item %}
{# render those elements in a different way #}
{% endblock %}

then in your root-dashboard.html, you use:

# root-dashboard.html
{% extend 'root.html' %}
{% block render_item %}
{# render some elements in a certain way #}
{% endblock %}

The idea is similar to the dynamic binding concept [wiki] in object-oriented programming, and is usually better than using if conditions: the latter is not extensible, and thus limits later modifications.

Back to Top