multiple images field ... how to iterate and change classes?

Created on 8 June 2023, over 1 year ago

this works fine

      {% set imageclasses = ["grayscale" ,"mx-auto" ,"opacity-80" ,"hover:opacity-100" ,"max-w-full" ,"h-auto"] %}
     {{ content.field_image|add_attr('image_attributes', {class: imageclasses}) }} 

this not

      {% for key, image in content.field_image if key|first != '#' %}
                            <div class="splide__slide">
                                    <div class="w-full px-4 text-center pb-3">
                                    <a href="#" target="_blank">
                                      {% set imageclasses = ["grayscale" ,"mx-auto" ,"opacity-80" ,"hover:opacity-100" ,"max-w-full" ,"h-auto"] %}
                                    {{ image|add_attr('image_attributes', {class: imageclasses}) }} 
                                    </a>
                                </div>
                            </div>
                        {% endfor %} 

any idea what to do in this scenario ?

πŸ’¬ Support request
Status

Active

Component

Code

Created by

πŸ‡¬πŸ‡·Greece agelospanagiotakis

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @agelospanagiotakis
  • πŸ‡ΊπŸ‡ΈUnited States rlhawk Seattle, Washington, United States

    Since you are adding classes directly to the image render array, rather than its parent image field, you don't need the Twig filter provided by this module. Something like this should work:

    {% for key, image in content.field_image|filter((value, key) => not (key starts with '#')) %}
      <div class="splide__slide">
        <div class="w-full px-4 text-center pb-3">
          <a href="#" target="_blank">
            {% set imageclasses = ["grayscale" ,"mx-auto" ,"opacity-80" ,"hover:opacity-100" ,"max-w-full" ,"h-auto"] %}
            {{ image|merge({'#item_attributes': {class: imageclasses}}) }}
          </a>
        </div>
      </div>
    {% endfor %}
    
  • Thank you, snippet from #2 is working and just saved me some headache while trying to add classes on the rendering of the first item of a multi value image field.

    {{ content.field_pictures.0|merge({'#item_attributes': {class: ['rounded-3', 'mb-3']}}) }}

    Thank you for sharing this.

  • Status changed to Fixed about 2 months ago
  • πŸ‡ΊπŸ‡ΈUnited States rlhawk Seattle, Washington, United States
  • Automatically closed - issue fixed for 2 weeks with no activity.

Production build 0.71.5 2024