Cache problem on entity view mode teaser I'm using two slightly different versions of a teaser of a node on two different pages. It's the same fields used for both, but different HTML around each field.

In both cases, I get the renderable array of my node this way :

$view_builder = \Drupal::entityTypeManager()-&gt;getViewBuilder('node');
$vars['renderable_node'] = $view_builder-&gt;view($referenced_node, 'teaser');


What I would like to have :


Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 2


The problem is when I flush caches, the cache is set for the first time rendering the teaser of my node, but on my other page it render the same version.

Here is what I have then :


Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 1


I looked into ['#cache']['max-age'] but I don't really want to set it to 0 because it's not appropriate for obvious performance reasons.

I see that there is also ['#cache']['keys'], ['#cache']['context'] and ['#cache']['tags'] but not sure what to do.
I ran into the same problem recently.
Adding a key to the ['#cache']['keys'] array as unique id solved my cache problem.
For your case it should be like this :

$view_builder = \Drupal::entityTypeManager()-&gt;getViewBuilder('node');
$vars['renderable_node'] = $view_builder-&gt;view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_1";


On your second call to the teaser node then it should be like this :

$view_builder = \Drupal::entityTypeManager()-&gt;getViewBuilder('node');
$vars['renderable_node'] = $view_builder-&gt;view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_2";