Calling number of images in image-caption-formatter.html.twig

Created on 31 October 2021, about 3 years ago
Updated 23 February 2024, 10 months ago

Depending on the number of images in a field I need different Twig code. > 1 image: code variant 1, = 1 image: code variant 2.
Can I query the number of images in the field in image-caption-formatter.html.twig?
If yes, how?

💬 Support request
Status

Active

Version

1.1

Component

Code

Created by

🇩🇪Germany deelite

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

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇮🇳India Madhu Kumar M E

    Hi ,

    below of this code will might help you for this kind scenario,
    You can create a preprocess function specifically for the image-caption formatter and pass the count of images as a variable to the Twig template. Here's how you can do it:

    use Drupal\Core\Field\FieldItemListInterface;
    /**
     * Implements hook_preprocess_HOOK() for image_caption_formatter.
     */
    function themeName_preprocess_image_caption_formatter(&$variables) {
      // Get the field items from the variables array.
      $items = $variables['items'];
      // Initialize a counter for the number of images.
      $imageCount = 0;
      // Loop through the field items to count the number of images.
      foreach ($items as $item) {
        if ($item instanceof FieldItemListInterface) {
          foreach ($item as $imageItem) {
            // Check if the item is an image.
            if ($imageItem->entity instanceof \Drupal\file\Entity\File) {
              $imageCount++;
            }
          }
        }
      }
      // Pass the image count variable to the template.
      $variables['image_count'] = $imageCount;
    }

    you can use the image_count variable to determine which code variant to render:

    {% if image_count > 1 %}
      {# Variant 1 code #}
    {% elseif image_count == 1 %}
      {# Variant 2 code #}
    {% endif %}
Production build 0.71.5 2024