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.
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().
Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.
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)
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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With