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.

2
  • Why not use two different display modes and use $view_builder->view($node, 'teaser'); and $view_builder->view($node, 'other_teaser');? Sep 13, 2017 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, 2017 at 15:28

1 Answer 1

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";
1
  • 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, 2017 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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