I am creating a module that will allow editors to display nodes as "cards" using the summary from the node for the card text and a field (field_hero) as a background image to the card, the user can then click-thru to the actual content from the card. The editor can also define, via the layout builder the colour behind the text for the card and also where the text appears (top, left, right, bottom).
If I add several of these cards to a page using the layout builder, all of the cards use the values for position and colour from the last instance placed on the page.
My code block plugin code is:
public function build() {
if ($entity_id = $this->configuration['entity']) {
if (($entity = $this->entityStorage->load($entity_id)) && $entity->access('view')) {
$render_controller = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
$view_mode = isset($this->configuration['view_mode']) ? $this->configuration['view_mode'] : 'default';
if (isset($this->configuration['card_colour'])) {
$entity->card_colour = $this->configuration['card_colour'];
}
if (isset($this->configuration['card_layout'])) {
$entity->card_layout = $this->configuration['card_layout'];
}
return $render_controller->view($entity, $view_mode);
}
}
return [];
}
And my twig template is (ignore the empty url() in the style attribute):
{%
set classes = [
'node-card',
'card-' ~ node.card_layout|clean_class,
node.card_colour|clean_class,
'clearfix'
]
%}
<article{{ attributes.addClass(classes) }}>
<div{{ content_attributes.addClass('bg-img', 'clearfix') }} style="background-image: url()">
<div class="summary">
{{ content.body }}
</div>
</div>
</article>