blazy_blurry_placeholder-8.x-2.1/src/Plugin/Field/FieldFormatter/BlazyBlurryPlaceholderImageFormatter.php
src/Plugin/Field/FieldFormatter/BlazyBlurryPlaceholderImageFormatter.php
<?php
namespace Drupal\blazy_blurry_placeholder\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\file\Entity\File;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;
/**
* Plugin implementation of the 'blazy_blurry_placeholder_image' formatter.
*
* @FieldFormatter(
* id = "blazy_blurry_placeholder_image",
* label = @Translation("Blazy Blurry Placeholder Image"),
* description = @Translation("Display a blurry placeholder of the image while lazy-loading it with bLazy."),
* field_types = {
* "image"
* }
* )
*/
class BlazyBlurryPlaceholderImageFormatter extends ImageFormatter {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = parent::viewElements($items, $langcode);
foreach ($elements as &$element) {
/** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $image_item */
$image_item = $element['#item'];
$element = [
'#theme' => 'blazy_blurry_placeholder_image',
'#image' => File::load($image_item->get('target_id')->getValue()),
'#image_style' => $element['#image_style'],
'#title' => $image_item->get('title')->getValue(),
'#alt' => $image_item->get('title')->getValue(),
'#url' => $element['#url'],
'#cache' => $element['#cache'],
];
}
$elements['#attached']['library'][] = 'blazy_blurry_placeholder/blazy';
return $elements;
}
}
