public function TwentyTwentyFormatter::viewElements in Glazed CMS Portfolio 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 FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ TwentyTwentyFormatter.php, line 162
Class
- TwentyTwentyFormatter
- Plugin implementation of the 'twentytwenty_field_formatter' formatter.
Namespace
Drupal\cms_portfolio\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$images = [];
$files = $this
->getEntitiesToView($items, $langcode);
// Early opt-out if the field is empty.
if (empty($files)) {
return $elements;
}
$image_style_setting = $this
->getSetting('image_style');
$elements['#attached']['drupalSettings']['twentytwenty']['default_offset_pct'] = $this
->getSetting('default_offset_pct');
// Collect cache tags to be added for each item in the field.
$cache_tags = [];
if (!empty($image_style_setting)) {
$image_style = $this->imageStyleStorage
->load($image_style_setting);
$cache_tags = $image_style
->getCacheTags();
}
foreach ($files as $delta => $file) {
if (isset($link_file)) {
$image_uri = $file
->getFileUri();
$url = Url::fromUri(file_create_url($image_uri));
}
$cache_tags = Cache::mergeTags($cache_tags, $file
->getCacheTags());
// 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;
$item_attributes = $item->_attributes;
unset($item->_attributes);
$images[$delta] = [
'#theme' => 'image_formatter',
'#item' => $item,
'#item_attributes' => $item_attributes,
'#image_style' => $image_style_setting,
'#cache' => [
'tags' => $cache_tags,
],
];
}
return [
'#theme' => 'cms_portfolio_twentytwenty',
'#images' => render($images),
'#attached' => [
'library' => [
'cms_portfolio/twentytwenty',
],
'drupalSettings' => [
'twentytwenty' => [
'default_offset_pct' => $this
->getSetting('default_offset_pct'),
],
],
],
];
}