1

Sometimes when I run below code in the hook_preprocess_menu() of a node, I am getting a previously loaded node instead of my current node.

\Drupal::routeMatch()->getParameter('node');

What should I do to stop this?

1

If you add node data in a preprocess hook, then you need to add the cache tag of the node:

$variables['node_title'] = [
  '#markup' => $node->getTitle(),
  '#cache' => [
    'tags' => $node->getCacheTags(),
  ],
];

If this node is from a route match, then you need to add a cache context for the route as well:

$node = \Drupal::routeMatch()->getParameter('node');
$variables['node_title'] = [
  '#markup' => $node->getTitle(),
  '#cache' => [
    'tags' => $node->getCacheTags(),
    'contexts' => ['route'],
  ],
];
  • Rather than just getting the cache tags, would it make sense to add the node as a cacheable dependency to also get any cache context or max-age settings from it? – Andy Jul 12 '18 at 16:07
  • @Andy, you can do this, but you only get a cache tag from the node and you need to add the context for the route yourself. If you write OOP code instead of hooks, then yes, use the methods the objects provide. – 4k4 Jul 12 '18 at 16:29
  • Can you assume you'll always only get a cache tag from the node - for example what if it's a translation, would it then not have a cache context on the language? – Andy Jul 12 '18 at 17:22

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.