问题
My menu needs some work. I need to have a class on the parent menu items, but with my recursion, it is not working.
This is (part of) my menu:
Home
Teachers (id teachers)
Contact
Info
Projects
myproject
yourproject
I start with "teachers" like this:
{% show_menu_below_id "teqchers" 0 1 0 1 "teachers_menu.html" %}
And this is my teachers_menu.html:
{% load menu_tags %}
{% for child in children %}
<li class="{% if child.selected %}selected parent_{{forloop.counter}}{% endif %} {% if child.sibling %}parent_{{forloop.counter}} {% endif %}">
<a href="{{ child.get_absolute_url }}">{{ child.get_menu_title }}</a>
{% if child.children %}
<div class="submenu">
<ul>
{% show_menu from_level to_level extra_inactive extra_active template "" "" child %}
</ul>
</div>
{% endif %}
</li>
{% endfor %}
With this in place, my menu is working for a bit.
When i click Projects, all is well and the 2 projects are in view. But when i click a project, i expect the page to show, but it does not, it does rebuild my menu, and adds the needed class to the child elements:
{% if child.selected %}selected parent_{{forloop.counter}}{% endif %}
Obvious because it is a child now i guess, but how to prevent this? I only need that class for the first menu items.
回答1:
Instead of doing this:
{% show_menu from_level to_level extra_inactive extra_active template "" "" child %}
I now added another template like this:
{% show_menu from_level to_level extra_inactive extra_active "teachers_submenu.html" "" "" child %}
And in that template I now have:
{% load menu_tags %}
{% for child in children %}
<li class="{% if child.selected %}selected{% endif %}">
<a href="{{ child.get_absolute_url }}">{{ child.get_menu_title }}</a>
</li>
{% endfor %}
So the extra template takes care of the submenu. With some styling it now works.
来源:https://stackoverflow.com/questions/27232567/django-cms-menu-how-to-set-a-class-to-parents-only