Twig for 循环 "this"

Twig for loop "this"

如何在 For 循环中使用传入的数据?

我想做这样的事情: (使用 "this" 无效)

{% for button in this %}
    Button in passed in array        
{% endfor %}

* 编辑 *

我有一个名为按钮组的树枝模板,其中有一个循环遍历传递到树枝模板的所有按钮。但是我无法遍历传入的任何数据。

我的嵌入:

{% if data.buttons %}
  {% embed "button-group.twig" data.buttons %}{% endembed %}
{% endif %} 

按钮-group.twig:

{% for button in this %} {# this should be the same as passed data.buttons #}
  <button>{{buttonText}}</button>
{% endfor %}

所有变量都在嵌入文件中可用。您可以简单地遍历 data.buttons,例如:

{# button-group.html.twig #}
{% for button in data.buttons %}
    <button>{{ buttonText }}</button>
{% endfor %}

但是您可以使用不同的名称显式传递变量:

{# skeleton.html.twig #}
{% embed "default/test.html.twig" with {buttons: data.buttons} only %}{% endembed %}

{# button-group.html.twig #}
{% for button in buttons %}
    <button>{{ buttonText }}</button>
{% endfor %}

关键字only表示只有传递的变量在嵌入模板中可用。如果省略,您可以在 button-group.html.twig.

中使用 buttonsdata.buttons

进一步阅读


注意:我在“embed”的 Twig 手册中找不到任何对自动生成变量 this 的引用。您当然可以使用 {this: data.buttons} 嵌入模板并自己创建。我不建议使用这个变量名,因为它可能会与 PHP 的 $this 混淆,另一方面,后者不能被重新赋值。


另一个注意事项:在您的循环中,您输出了一个名为 buttonText 的变量,该变量未在您的示例中定义。您可能需要根据 data-buttons 保留的内容将其更改为 buttonbutton.text 之类的内容。