How do you prevent twig variable from last instance of template overriding those that go before it? 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-&gt;configuration['entity']) {
  if (($entity = $this-&gt;entityStorage-&gt;load($entity_id)) &amp;&amp; $entity-&gt;access('view')) {
    $render_controller = \Drupal::entityTypeManager()-&gt;getViewBuilder($entity-&gt;getEntityTypeId());
    $view_mode = isset($this-&gt;configuration['view_mode']) ? $this-&gt;configuration['view_mode'] : 'default';

    if (isset($this-&gt;configuration['card_colour'])) {
      $entity-&gt;card_colour = $this-&gt;configuration['card_colour'];
    }
    if (isset($this-&gt;configuration['card_layout'])) {
      $entity-&gt;card_layout = $this-&gt;configuration['card_layout'];
    }

    return $render_controller-&gt;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'
    ]
%}
&lt;article{{ attributes.addClass(classes) }}&gt;
    &lt;div{{ content_attributes.addClass('bg-img', 'clearfix') }} style="background-image: url()"&gt;
        &lt;div class="summary"&gt;
            {{ content.body }}
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/article&gt;
$render_controller->view() invokes hook_ENTITY_TYPE_view() and this would be a better place to add custom values to the entity view.

Although probably not good practice you could get your approach working by cloning the entity before modifying the field values:

$entity = clone $entity;


In any case you need to adjust caching so that you store for each variant a different cache item in the render cache. For example by adding cache keys to the build array before returning it:

$build = $render_controller-&gt;view($entity, $view_mode);
if (isset($entity-&gt;foo)) {
  $build['#cache']['keys'][] = $entity-&gt;foo;
}
return $build;