Score:1

Calling a twig template depending on the number of field items

cn flag

I need to call different twig templates of an image field depending on the number of items of this field. If there is only 1 image item, I'd like to use template1.html.twig. If there are > 1 image items, I'd like to use template2.html.twig.

Is that possible? If yes, how?

cn flag
Can you use length to do conditional logic in the template? https://twig.symfony.com/doc/2.x/filters/length.html In other words, one template, but you use length to count the number of items and then process it differently based on that.
cn flag
I know the usage of length - this would be my solution when I know how to call different templates. I don't know the code to call 2 different templates when there is only 1 (from a module) and absolutely know file (alter) name suggestions.
Score:3
ne flag

Sounds like a simple template suggestion added from a custom module or theme along the following snippet.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#field_name'] === 'field_MYFIELD') {
    // Fallback.
    $values = '';

    /** @var \Drupal\Core\Field\FieldItemList $items */
    $items = $variables['element']['#items'];
    if ($items->count() == 1) {
      $values = '__single_image';
    }
    if ($items->count() > 1) {
      $values = '__slideshow';
    }

    $suggestions[] = 'field__' . $variables['element']['#field_name'] . $values;
  }
}

This would allow you to have field--field-MYFIELD--single-image.html.twig or field--field-MYFIELD--slideshow.html.twig.

Flush cache!

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.