Select menu item based on current view

I am currently checking a variable in the template for each menu item to find out 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 will have to repeat the above code four times.

"menu":[
{"title":"home", "link":"/"}, 
{"title":"about", "link":"about"}, 
{"title":"contact","link":"contact"}
]

Is there an easier way to iterate over a list and select the corresponding item?

+4
source share
1 answer

Instead of passing something or trying to parse any URL or list, just make the highlighted part of the template.

Create a basic template containing a menu, with a block for each property class=.

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

, , "active".

{% extends "base.html" %}
{% block nav_contact %}active{% endblock %}
{% block content %}<h3>Contact</h3>{% endblock %}
+7

Source: https://habr.com/ru/post/1584961/


All Articles