You are here

public function ImageUrlFormatter::viewElements in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php \Drupal\image\Plugin\Field\FieldFormatter\ImageUrlFormatter::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides ImageFormatter::viewElements

File

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

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\file\FileInterface[] $images */
  foreach ($images as $delta => $image) {
    $image_uri = $image
      ->getFileUri();
    $url = $image_style ? $image_style
      ->buildUrl($image_uri) : file_create_url($image_uri);
    $url = file_url_transform_relative($url);

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