Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a parent template that contains a generic navigation menu. I want to be able to add class="selected" to the appropriate menu option.

I want to be able to set a variable in a child template, for example:

{% set menu = "products" %}

and do:

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

I don't want to set a value in the View because I would have to add this to all my view methods, and I dont want to repeat the entire menu html in each child page because if the menu changes I only want to change the HTML in one place.

Am I approaching this from a “non-Django” mind-set?

Any help would be really appreciated. thanks.

like image 435
Tom Carnell Avatar asked Feb 09 '10 12:02

Tom Carnell


People also ask

How do you make a variable available to all templates in Django?

If you need to make it available in some_other_template. html, all you need to do is to pass the RequestContext object as the third parameter to render_to_reponse().

How do you pass variables from Django view to a template?

Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.

How do I add a variable to a template?

Choose Template > New Variable from the editor toolbar (or choose an existing variable to add it to the page) Enter a name for the variable. Press Enter (by default this will create a single-line text input field)

Can we create a variable in Django template?

We can set the value of a variable in the Django template using with tag. This will output the below content. One downside of this approach is that we have to write the lines where we are accessing the variable inside with and endwith block. Using with is useful when using a costly variable multiple times.


2 Answers

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 %}
like image 88
Jiaaro Avatar answered Sep 28 '22 19:09

Jiaaro


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 %}
like image 33
speakman Avatar answered Sep 28 '22 19:09

speakman