Django templates - can I set a variable to be used in a parent template? Django templates - can I set a variable to be used in a parent template? django django

Django templates - can I set a variable to be used in a parent template?


for the record, it is considered a bad practice... but you can do this

{% with "products" as menu %}    {{ menu }}{% endwith %}

Since that doesn't actually solve your specific problem here is a possible application...

<div class='menu'>    {% block menuitems %}        <a class='{% ifequal menu 'products' %}selected{% endifequal %}' href='/whereever/'>products</a>        ...    {% endblock %}</div>

and in the child template

{% block menuitems %}    {% with 'products' as menu %}        {{ block.super }}    {% endwith %}{% endblock %}


The context you pass within you view is also available in the templates you're extending. Adding a 'menu_class': 'selected' in the context, you could set

<div id="menu" class="{{ menu_class }}">

in the base template.

Another way around would be

<div id="menu" class="mymenu {% block menu_attrib %}{% endblock %}">

which then is extendible in your child template by

{% block menu_attrib %}selected{% endblock %}


There is more than one answer here of course!

You could use custom template tags to both draw the menu and select the appropriate one.

So your template tag would be:

{% mymainmenu selecteditem %}

Have a look at the custom template tag documentation on the django site, but it would end up something like:

@register.simple_tagdef mymainmenu(selecteditem):    html = ''    build the html for the menu here and include selected class    return html