遍历Twig中的子元素,例如Element :: children()


9

在PHP中处理可渲染数组时,我可以使用Element :: children()来访问不是#属性而是从属可渲染元素的元素(字段集中的表单项,字段小部件内的项等)。例如,来自file.module的此代码段:

<?php
if ($element['#multiple']) {
  foreach (Element::children($element) as $name) {
    // ...
  }
}
?>

如何在Twig模板中做同样的事情?如果我这样做{% for child in element %},它也将包括#type#cache等等。


Answers:


21
{% for key, child in element if key|first != '#' %}
  <div>{{ child }}</div>
{% endfor %}

2
请避免仅使用代码的答案。
Mołot

2

我创建了一个Twig过滤器,该过滤器以孩子的身份返回ArrayIterator

mymodule/mymodule.services.yml

services:
  mymodule.twig_extension:
    arguments: ['@renderer']
    class: Drupal\mymodule\TwigExtension\Children
    tags:
      - { name: twig.extension }


mymodule/src/TwigExtension/Children.php

<?php

namespace Drupal\mymodule\TwigExtension;


class Children extends \Twig_Extension
{

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters()
  {
    return [
      new \Twig_SimpleFilter('children', array($this, 'children')),
    ];
  }


  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName()
  {
    return 'mymodule.twig_extension';
  }


  /**
   * Get the children of a field (FieldItemList)
   */
  public static function Children($variable)
  {
    if (!empty($variable['#items'])
      && $variable['#items']->count() > 0
    ) {
      return $variable['#items']->getIterator();
    }

    return null;
  }

}


在Twig模板中:

{% for headline in entity.field_headline|children %}
  {{ headline.get('value').getValue() }}
{% endfor %}

2

使用Twig Tweak模块,该模块除其他出色功能外,还具有“子级”过滤器:

{% for item in content.field_name | children(true) %}
  {# loop.length, loop.revindex, loop.revindex0, and loop.last are now available #}
{% endfor %}

1

这是对https://drupal.stackexchange.com/a/236408/67965的修改,它循环遍历渲染子对象而不是字段#items

树枝延伸:

/**
 * Generates a list of all Twig filters that this extension defines.
 */
public function getFilters() {
  return [
    new \Twig_SimpleFilter('children', array($this, 'children')),
  ];
}

/**
 * Get the render children of a field
 */
public static function children($variable) {
  return array_filter(
    $variable, 
    function($k) { return (is_numeric($k) || (strpos($k, '#') !== 0)); },
    ARRAY_FILTER_USE_KEY
  );
}

然后,在树枝中,您可以直接通过渲染的子代,这有助于实现原子设计模式。定义一个实体模板,例如:

{% include '@molecules/grid.html.twig' with { 
   head : content.field_title,
   grid_columns: content.field_collection_items|children
} %}

其中grid.html.twig是这样的:

{% if head %}
<div class="slab__wrapper">
  {{ head }}
</div>
{% endif %}
<div class="grid">          
  {% for col in grid_columns %}
  <div class="grid__column">
    {{ col }}
  </div>
  {% endfor %}
</div>

这通常比必须渲染字段模板更有用,{{ content.field_collection_items }}因为可以在父级设计元素的上下文中控制子级的布局。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.