0

I want get the current page and give an active class without duplicate code in symfony 5. Here is the code example :

    <li class="{{ app.request.get('_route_')=='home' ? 'active':''}}">
       <a href="{{path('home')}}">Home</a> 
   </li>
    <li class="{{ app.request.get('_route_')=='contact' ? 'active':''}}">
        <a href="{{path('contact')}}">Contact</a> 
    </li>

</ul>
Salif
  • 1
  • 3

2 Answers2

1

As an extension of the answer of @DhiaDjobbi

I've you really want to reduce "duplicate" code, I'd go with defining the menu in an array as well

{% set active_page = app.request.get('_route') %}
{% for page in pages %}
    <li  {% if page == active_page %} class="active" {% endif %} >
        <a href="{{path(page)}}">{{ page }}</a> 
    </li>
{% endfor %}
DarkBee
  • 16,592
  • 6
  • 46
  • 58
0

U can create a twig variable in Template its better readable.

{% set page = app.request.get('_route') %}

Then use If Condition to test.

<li  {% if page == 'home' %} class="active" {% endif %} >
   <a href="{{path('home')}}">Home</a> 
</li>
<li  {% if page == 'contact' %} class="active" {% endif %} >
   <a href="{{path('contact')}}">Contact</a> 
</li>
Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35