передайте пользовательскую переменную для поля изображения из узла предварительной обработки в ветку


У меня есть тип контента (gallery) с неограниченным полем изображения: field_picture.
У меня есть логика, которая вычисляет пользовательские классы css для их HTML-контейнеров, например: grid-item--width1, grid-item--width2, grid-item--height1, grid-item--height2.
Я храню их в grid_class.
Я не могу объединить эти классы с классом item, потому что я хочу, чтобы они создавали разные HTML-контейнеры.

Я попытался добавить эту новую переменную (grid_class) к элементам изображения из mytheme_preprocess_node__gallery, и я подумал, что drupal8 будет передайте их в шаблон ветки.

function mytheme_preprocess_node__gallery(&$variables)
{
  foreach (Element::children($variables['elements']['field_picture']) as $key) {
    // here is my logic which calculates the classes for the image elements' containers
    $grid_class = "grid-item--width1 grid-item--height1";
    $variables['elements']['field_picture'][ $key ]['grid_class'] = $grid_class;
  }
}

Но в моем шаблоне ветки (themes/custom/mytheme/templates/field/field--node--field-picture--gallery.html.twig), когда я перебираю items, grid_class недоступен.

{% for key, item in items %}

    {{ (dump(item)) }}

    <div{{ item.attributes }}>
      <div class="grid-item {{ item.grid_class }}">{{ item.content }}</div>
    </div>
{% endfor %}

Я также попытался добавить его из mytheme_preprocess_field(). Я видел массив элемента field_picture, но я не нашел там элементов.

Какая-нибудь помощь или подсказки?

 1
Author: Zoltán Süle, 2017-06-01

1 answers

Я обнаружил, что мне нужно использовать крючок mytheme_preprocess_field.

function mytheme_preprocess_field(&$variables) {
  if ($variables['field_name'] == "field_picture") {
    foreach ($variables['items'] as $key => $item) {
      $grid_class = "grid-item--width1 grid-item--height1";
      $variables['items'][ $key ]['grid_class'] = $grid_class;
    }
  }
}
 1
Author: Zoltán Süle, 2017-06-01 19:05:21