I'm currently checking a variable in the template on each menu item to see if I should add a CSS class to highlight it.
{% if title == "Home" %}
<li class="active">
{% else %}
<li>
{% endif %}
I want to create a list containing four menu items. To get the desired effect I'm going to have to repeat the above code four times.
"menu":[
{"title":"home", "link":"/"},
{"title":"about", "link":"about"},
{"title":"contact","link":"contact"}
]
Is there a simpler way to cycle through the list and highlighting the appropriate item?
Rather than passing anything, or trying to parse some url or list, just make the highlight part of the template.
Create a base template that contains the menu, with a block for each class=
property.
<ul>
<li class="{% block nav_home %}{% endblock %}">Home</li>
<li class="{% block nav_about %}{% endblock %}">About</li>
<li class="{% block nav_contact %}{% endblock %}">Contact</li>
</ul>
In the page templates that extend the base, override one of the blocks with the value "active".
{% extends "base.html" %}
{% block nav_contact %}active{% endblock %}
{% block content %}<h3>Contact</h3>{% 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