【问题标题】:How to get current page in pages Symfony 5 without duplicate code?如何在没有重复代码的情况下获取 Symfony 5 页面中的当前页面?
【发布时间】:2021-01-19 11:11:05
【问题描述】:
我想获取当前页面并在 symfony 5 中提供一个没有重复代码的活动类。
这是代码示例:
<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>
【问题讨论】:
标签:
symfony
navigation
twig
current-page
【解决方案1】:
作为@DhiaDjobbi 答案的延伸
我真的想减少“重复”代码,我也会在数组中定义菜单
{% 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 %}
【解决方案2】:
你可以在 Template 中创建一个更易读的 twig 变量。
{% set page = app.request.get('_route') %}
然后使用 If Condition 进行测试。
<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>