树枝从数组创建菜单项

twig create menu items from array

在 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.")

With path({{ 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

您已经 {{ {{ path
在 twig 中,{{ 等于 php 函数 echo.
就像 <?php echo <?php echo "oops"

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

问题

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

解决方案

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

示例:比较 BeforeAfter

之前

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

之后

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

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

{% 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. 你的 array-like 应该是 Iterable 所以使用 links= [...]
  2. 数组中的变量(键)应该被引用(因为你正在添加它们)
  3. 正如上面提到的在路径附近你已经在一个块中所以去掉引号(你指的是一个 var)和 {{ }}
  4. 最后一个“,”不是强制性的(一些 twig 实现认为它是错误的)