function ImageUrlFormatter::viewElements

Same name in other branches
  1. 9 core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php \Drupal\image\Plugin\Field\FieldFormatter\ImageUrlFormatter::viewElements()
  2. 8.9.x core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php \Drupal\image\Plugin\Field\FieldFormatter\ImageUrlFormatter::viewElements()
  3. 11.x core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php \Drupal\image\Plugin\Field\FieldFormatter\ImageUrlFormatter::viewElements()

Overrides FormatterInterface::viewElements

File

core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php, line 149

Class

ImageUrlFormatter
Plugin implementation of the 'image_url' formatter.

Namespace

Drupal\image\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items */
    if (empty($images = $this->getEntitiesToView($items, $langcode))) {
        // Early opt-out if the field is empty.
        return $elements;
    }
    
    /** @var \Drupal\image\ImageStyleInterface $image_style */
    $image_style = $this->imageStyleStorage
        ->load($this->getSetting('image_style'));
    
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    
    /** @var \Drupal\file\FileInterface[] $images */
    foreach ($images as $delta => $image) {
        $image_uri = $image->getFileUri();
        $url = $image_style ? $file_url_generator->transformRelative($image_style->buildUrl($image_uri)) : $file_url_generator->generateString($image_uri);
        // Add cacheability metadata from the image and image style.
        $cacheability = CacheableMetadata::createFromObject($image);
        if ($image_style) {
            $cacheability->addCacheableDependency(CacheableMetadata::createFromObject($image_style));
        }
        $elements[$delta] = [
            '#markup' => $url,
        ];
        $cacheability->applyTo($elements[$delta]);
    }
    return $elements;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.