【问题标题】:twig create menu items from array树枝从数组创建菜单项
【发布时间】:2017-06-13 05:32:58
【问题描述】:

在 Symfony 3.2(使用 twig)中,我试图从数组中动态生成菜单项。

数组:

  {% set links = {
      dashboard: { path: 'dashboard', title: 'Home' },
      page1: { path: 'page1', title: 'Page1' },
      page2: { path: 'page2', title: 'Page1' },
    }
  %}

菜单项循环:

        {% for link in links %}
          <li>
            <a {% if app.request.attributes.get('_route') == link.path %}
                class="active"
               {% endif %} 
               href="{{ path('{{link.path}}') }}">{{ link.title }}
            </a>
          </li>
        {% endfor %}

我收到错误An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "{{link.path}}" as such route does not exist.")

使用路径({{ link.path }})我收到错误A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{" in

【问题讨论】:

    标签: loops syntax twig template-engine


    【解决方案1】:

    问题

    • 开发人员在将变量传递给 Twig 函数时收到错误消息。

    解决方案

    • 注意 Twig 表达式和模板占位符的语法
    • 在函数内声明时,twig 变量不需要使用花括号占位符语法进行转义。

    示例:比较 BeforeAfter

    之前

    href="{{ path('{{link.path}}') }}">{{ link.title }}

    之后

    href="{{ path(link.path) }}">{{ link.title }}

    【讨论】:

    • 这修复了它,我接受这个因为更干净的答案。 @goto 也有正确答案,除了需要在 path() 中删除 ' '
    【解决方案2】:

    您已经在{{ path 中拥有{{
    在 twig 中,{{ 等于 php 函数 echo。
    这就像拥有&lt;?php echo &lt;?php echo "oops"

    href="{{ path(link.path) }}">{{ link.title }}
    

    【讨论】:

    • 这也解决了上面的答案,除了你需要在 path() 中放置 ''
    【解决方案3】:

    您的树枝包含一些错误,请尝试以下操作

    {% set links = [
     { "path": 'dashboard', "title": 'Home' },
     { "path": 'page1', "title": 'Page1' }
    ] %}
    {% for link in links %}
       <li>
         <a 
            href="{{ path(link.path) }}">{{ link.title }}
         </a>
      </li>
    {% endfor %}
    
    1. 您的类数组应该是可迭代的,因此请使用 links= [...]
    2. 应引用数组中的变量(键)(因为您要添加它们)
    3. 如上所述,您已经在一个块内的路径附近,因此请删除引号(您指的是 var)和 {{ }}
    4. 最后一个“,”不是强制性的(一些 twig 实现认为这是一个错误)

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多