Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight menu item based on current view

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?

like image 973
Philip Kirkbride Avatar asked Jan 09 '23 12:01

Philip Kirkbride


1 Answers

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 %}
like image 111
davidism Avatar answered Jan 20 '23 09:01

davidism