You are here

public function BlazyFormatterTrait::viewElements in Blazy 8

File

src/Plugin/Field/FieldFormatter/BlazyFormatterTrait.php, line 18

Class

BlazyFormatterTrait
A Trait common for blazy image and file ER formatters.

Namespace

Drupal\blazy\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $build = [];
  $files = $this
    ->getEntitiesToView($items, $langcode);

  // Early opt-out if the field is empty.
  if (empty($files)) {
    return $build;
  }

  // Collects specific settings to this formatter.
  $settings = $this
    ->buildSettings();
  $settings['blazy'] = TRUE;
  $settings['namespace'] = $settings['item_id'] = $settings['lazy'] = 'blazy';
  $settings['_grid'] = !empty($settings['style']) && !empty($settings['grid']);

  // Build the settings.
  $build = [
    'settings' => $settings,
  ];

  // Modifies settings.
  $this->blazyManager
    ->buildSettings($build, $items);

  // Build the elements.
  $this
    ->buildElements($build, $files);

  // Updates settings.
  $settings = $build['settings'];
  unset($build['settings']);

  // Supports Blazy multi-breakpoint images if provided.
  $this->blazyManager
    ->isBlazy($settings, $build[0]['#build']);

  // Build grid if provided.
  if (empty($settings['_grid'])) {
    $build['#blazy'] = $settings;
  }
  else {
    $build = BlazyGrid::build($build, $settings);
  }
  $build['#attached'] = $this->blazyManager
    ->attach($settings);
  return $build;
}