1
votes

I have created a custom module that uses a custom block to display a list of nodes (I can't use D8 views in this particular case). Inside the block twig template I need to filter this list on the current nid (node id of the current page) and I'm passing the value to twig in this way:

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;
return array(
        'currentnid' => $nid,
    );

Everything is working fine, but changing page the nid passed to the block template is still the same. I think this is related to template caching: by clearing the cache and reloading the page I get the correct value for the current page, but moving to another page I'm still getting the same nid! Is there something I can do to prevent nid value to be cached? I think that the best solution would be to get the current nid value directly inside the template, but I'm inside the custom block and I don't know how to get it. Any idea? I have already checked the kint() output and the current page nid is not present at the block template level.

2
Maybe you should ask on drupal.stackexchange.com - malcolm
Thanks a lot @malcolm I didn't know that site, I'll try for sure. - Gabriele

2 Answers

2
votes
<?php
namespace Drupal;
$node_v1 = \Drupal::request()->attributes->get('node');
$node_v2 = \Drupal::routeMatch()->getParameter('node')

?>
1
votes

in your build array try using cache tags with your current nid

return array(
    'currentnid' => $nid,
    '#cache' => [
        'tags' => ['node:'.$nid],
    ],
);