[Fixed]-Django templates – can I set a variable to be used in a parent template?

10👍

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 %}
👤Jiaaro

9👍

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 %}

1👍

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_tag
def mymainmenu(selecteditem):

    html = ''

    build the html for the menu here and include selected class

    return html

0👍

Thanks everyone – in the end I followed speakman’s suggestion and put the name of the current menu option in thew context and use my:

{%ifequal menu "products" %}
    class="selected"
{% endifequal %}

clause in each menu opton.

I don’t think this is a great solution, it couples my ‘views’ to my ‘templates’ more than I would have liked…but maybe this is just s django quirk

0👍

You can use a custom template tag as described here:
http://www.soyoucode.com/2011/set-variable-django-template

Leave a comment