public function AutoImageStyleMediaDefault::viewElements in Auto image style 8
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
- src/
Plugin/ Field/ FieldFormatter/ AutoImageStyleMediaDefault.php, line 145
Class
- AutoImageStyleMediaDefault
- Plugin for responsive media image formatter.
Namespace
Drupal\auto_image_style\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$files = $this
->getEntitiesToView($items, $langcode);
// Early opt-out if the field is empty.
if (empty($files)) {
return $elements;
}
$url = NULL;
$image_link_setting = $this
->getSetting('image_link');
// Check if the formatter involves a link.
if ($image_link_setting == 'content') {
$entity = $items
->getEntity();
if (!$entity
->isNew()) {
$url = $entity
->toUrl();
}
}
elseif ($image_link_setting == 'media') {
$link_file = TRUE;
}
$image_style_landscape_setting = $this
->getSetting('image_style_landscape');
$image_style_portrait_setting = $this
->getSetting('image_style_portrait');
// Collect cache tags to be added for each item in the field.
$cache_tags = [];
if (!empty($image_style_landscape_setting)) {
$image_style = $this->imageStyleStorage
->load($image_style_landscape_setting);
$cache_tags_landscape = $image_style
->getCacheTags();
$cache_tags = Cache::mergeTags($cache_tags, $cache_tags_landscape);
}
if (!empty($image_style_portrait_setting)) {
$image_style = $this->imageStyleStorage
->load($image_style_portrait_setting);
$cache_tags_portrait = $image_style
->getCacheTags();
$cache_tags = Cache::mergeTags($cache_tags, $cache_tags_portrait);
}
/** @var \Drupal\media_entity\MediaInterface $media_item */
foreach ($files as $delta => $file) {
$cache_tags = Cache::mergeTags($cache_tags, $file
->getCacheTags());
// Link the <picture> element to the original file.
if (isset($link_file)) {
$url = file_url_transform_relative(file_create_url($file
->getFileUri()));
}
// Extract field item attributes for the theme function, and unset them
// from the $item so that the field template does not re-render them.
$item = $file->_referringItem;
$image_style = $image_style_portrait_setting;
if ($item->height < $item->width) {
$image_style = $image_style_landscape_setting;
}
$elements[$delta] = [
'#theme' => 'image_formatter',
'#item' => $item,
'#item_attributes' => [],
'#image_style' => $image_style,
'#url' => $url,
];
}
return $elements;
}