1

I have a content type (gallery) with an image field which is unlimited: field_picture.
I have a logic which calculates custom css classes to their HTML containers, like: grid-item--width1, grid-item--width2, grid-item--height1, grid-item--height2.
I store these in the grid_class.
I can't merge these classes with the item class, because I want to style different HTML containers by them.

I tried to add this new variable (grid_class) to the image elements from the mytheme_preprocess_node__gallery and I thought drupal8 will pass them to the twig template.

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;
  }
}

but in my twig template (themes/custom/mytheme/templates/field/field--node--field-picture--gallery.html.twig) when I loop through the items, the grid_class isn't available.

{% for key, item in items %}

    {{ (dump(item)) }}

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

I also tried to add it from mytheme_preprocess_field(). I saw the array of the field_picture element, but I didn't find the items in there.

any help or hints?

1 Answer 1

1

I found that I have to use the mytheme_preprocess_field hook.

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;
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.