Warm tip: This article is reproduced from serverfault.com, please click

Symfony, Twig, if conditions for tab highlights according to current route

发布于 2014-06-30 17:53:54

I am trying to get a list to highlight if it is at its current page (route). However, I also have subpages within the pages of which I also want the list to be highlighted.

I have my menu if statements:

 <ul class="menu">
                {% if app.request.get('_route') == 'home' %}
                    <li class="current"><a href="{{ path('home')}}">Home</a></li>
                {% else %}
                    <li><a href="{{ path('home')}}">Home</a></li>
                {% endif %}

                {% if app.request.get('_route') == 'reports' %}
                    <li class="current"><a href="{{ path('reports') }}">Reports</a></li>
                {% else %}
                    <li><a href="{{ path('reports') }}">Reports</a></li>
                {% endif %}

// etc etc 

Now in my reports page, the route is /reports/ I have a menu that clicks to "Detail", "Summary", etc it will go to /reports/detail and /reports/summary... I want it so that when users click on those links, the main navigation is still highlighted.

I was wondering if there is an if statement condition something like this:

{% if app.request.get('_route') starts with(?) 'reports' %}

So whenever anyone goes to a route that's a sub page of /reports/, the "Reports" li in the menu will still be highlighted?

Questioner
user3757305
Viewed
0
FuzzyTree 2014-07-01 02:17:48

I'm not sure if twig has a function for "starts with" but you can check for containment using in

{% if 'reports' in app.request.get('_route')  %}