【问题标题】: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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 2021-12-10
        • 2016-07-02
        • 2010-10-10
        • 2010-11-19
        • 1970-01-01
        • 2011-08-12
        相关资源
        最近更新 更多