protected function PictureBackgroundFormatter::build_element in Picture Background Formatter 8
Build the inline css style based on a set of files and a selector.
Parameters
\Drupal\Core\Entity\EntityInterface[] $files: The array of referenced files to display, keyed by delta.
\Drupal\Core\Entity\EntityInterface $entity: The parent entity the field belongs to. Used for token replacement in the selector.
Return value
array
2 calls to PictureBackgroundFormatter::build_element()
- PictureBackgroundFormatter::viewElements in src/
Plugin/ Field/ FieldFormatter/ PictureBackgroundFormatter.php - Builds a renderable array for a field value.
- PictureBackgroundFormatterMedia::viewElements in src/
Plugin/ Field/ FieldFormatter/ PictureBackgroundFormatterMedia.php - Builds a renderable array for a field value.
File
- src/
Plugin/ Field/ FieldFormatter/ PictureBackgroundFormatter.php, line 114
Class
- PictureBackgroundFormatter
- Plugin implementation of the 'picture_background_formatter' formatter.
Namespace
Drupal\picture_background_formatter\Plugin\Field\FieldFormatterCode
protected function build_element($files, $entity) {
$elements = [];
$css = "";
$selector = $this
->getSetting('selector');
$selector = \Drupal::token()
->replace($selector, [
$entity
->getEntityTypeId() => $entity,
], [
'clear' => TRUE,
]);
// Collect cache tags to be added for each item in the field.
$responsive_image_style = $this->responsiveImageStyleStorage
->load($this
->getSetting('responsive_image_style'));
$image_styles_to_load = [];
$cache_tags = [];
if ($responsive_image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $responsive_image_style
->getCacheTags());
$image_styles_to_load = $responsive_image_style
->getImageStyleIds();
}
$image_styles = $this->imageStyleStorage
->loadMultiple($image_styles_to_load);
foreach ($image_styles as $image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $image_style
->getCacheTags());
}
foreach ($files as $file) {
$css .= $this
->generate_background_css($file, $responsive_image_style, $selector);
}
if (!empty($css)) {
// Use the selector in the id to avoid collisions with multiple background
// formatters on the same page.
$id = 'picture-background-formatter-' . $selector;
$elements['#attached']['html_head'][] = [
[
'#tag' => 'style',
'#value' => new CSSSnippet($css),
],
$id,
];
}
return $elements;
}