0

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()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->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.

  • Why not use two different display modes and use $view_builder->view($node, 'teaser'); and $view_builder->view($node, 'other_teaser');? – Neograph734 Sep 13 '17 at 15:09
  • That's a good remark indeed, but in my case, I'm in a preprocess_node where I render a node teaser from an other type. Some info differ based on the current node. – pbonnefoi Sep 13 '17 at 15:28
1

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()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->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()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_2";
  • That sounds good indeed ! In my case, I use the current nid of my preprocess node to make a difference $vars['renderable_node']['#cache']['keys'][] = $current_node->id(); – pbonnefoi Sep 13 '17 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.