Home > database >  Find on which item route from the menu I am
Find on which item route from the menu I am

Time:11-27

I'm currently working on a Symfony 4.4 web application.

The menu can be changed by the administrators of my app, so there is a table with these properties :

enter image description here

Because I got routes with some parameters (eg: a slug or an id, and the slug can change so it's not a great identifier).

The problem is that I want to know on which menu item I am, to keep the menu opened (to add an active class on < li > items) but I can't find a way to do it properly.

What I tried :

Identify the route with something like that :

<li>{% if app.request.get('_route') == 'foo_products_overview' and app.request.get('slug') in ["entityslug"] %} class="active" {% endif %}></li>

But parameters are not the same for each route of my app (mutliple entites using id or slug to find one).

Here is the way my menu items are displayed :

{% if child2.getMenuItems()|length > 0 %}
    <ul class="collapse nav-sub" aria-expanded="false">
        {% for child3 in child2.getMenuItems() if child2.getMenuItems()|length > 0 and child3.level == 4 and (is_granted(child3.roles) or child3.roles is empty) %}
            <li class="{% if child3.getMenuItems()|length > 0 %}nav-dropdown{% endif %}">
                <a hljs-keyword">if child3.getMenuItems()|length > 0 %}has-arrow{% endif %}"
                    href="{% if child3.route is not null %}{% if child3.routeParameters %}{{ path(child3.route, {'id': child3.routeParameters}) }}{% else %}{{ path(child3.route) }}{% endif %}{% else %}#{% endif %}"
                    aria-expanded="false">
                    <span>{% if "ROLE_ADMIN" in child3.roles %}<i class="la la-eye-slash text-danger mr-2"></i>{% endif %}{{ child3.name|raw }}</span>
               </a>
           </li>
        {% endfor %}
     </ul>
  {% endif %}

Have you ever had this problem?

Maybe there's a way with KnpMenu? (https://symfony.com/bundles/KnpMenuBundle/current/index.html) I'm not using it for the moment.

CodePudding user response:

Did you try this : replace "child.id" by your variable name, i think that's "child3.id" but not sure.

class="{% if app.request.attributes.get( '_route' ) starts with 'foo_products_overview' and app.request.attributes.get('id') == child.id %}active{% endif%}"
  • Related