I have a custom module that run this code in the my_module.module file

function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'block__my_template' => array(
      'template' => 'block--my-template',
      'variables' => array(
        'node_id' => \Drupal::routeMatch()->getParameter('node')->id(),

I am trying to pass the current node id to the template but the value is null. If I do a var_dump(\Drupal::routeMatch()->getParameter('node')->id()) it prints out the current node id so the function works.

My template does this:

<p>Node Id: {{ node_id }}</p>

Why aren't my variables passed to the template? What am I missing?

  • 1
    Because that's a cached definition of your module's theme items - it's only evaluated when the theme registry is being rebuilt, not every time the associated HTML is rendered. You can provide a default value in hook_theme, but evidently whatever context your cache is being cleared in isn't on a node page, so you get null for that. It's not a good idea to rely on that quirk even if it did work, save yourself the headache and use a preprocess function to pass dynamic vars instead – Clive Feb 6 '17 at 17:48
  • I am importing the twig template in another twig template. What preprocess function should I use then? – harnamc Feb 6 '17 at 22:17
  • The preprocess function for that particular theme item. If the other template is from the foo theme item, the function is MYMODULE_preprocess_foo – Clive Feb 7 '17 at 7:55

Your Answer

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

Browse other questions tagged or ask your own question.