2

I'd like to pass a variable to an overridden Twig template that is located in my custom module (not in a theme).

Following this answer and this answer, I wrote this code in mymodule.module:

function mymodule_preprocess_page(array &$variables) {
  $variables['hello'] = 'world';
}

function mymodule_theme_suggestions_node_add_list(array $variables) {
  $suggestions = [];
  $suggestions[] = 'node_add_list__' . 'custom';
  return $suggestions;
}

function mymodule_theme() {
  return [
    'node_add_list__custom' => [
      'base hook' => 'node_add_list',
    ],
  ];
}

Then, I have added in mymodule/templates/node-add-list--custom.html.twig:

myvar: {{ hello }}

However nothing appears after "myvar: " when I refresh the page. I mention that I cleared the cache.

Is there something specific to manage when we use hook_preprocess_page() with hook_theme_suggestions_HOOK()/hook_theme()?

2
  • 1
    You’re adding a variable to the “page” template - that’s not going to be available in other templates, just derivatives of page.html.twig.
    – Clive
    Oct 8, 2018 at 10:09
  • Try to take a look at this page, drupal.stackexchange.com/questions/186010/…
    – user72672
    Oct 8, 2018 at 10:12

1 Answer 1

3

You need to function MYMODULE_preprocess_node_add_list.

function MYMODULE_preprocess_node_add_list(array &$variables) {
  $variables['hello'] = 'world';
}

This preprocess hook is actually called HOOK_preprocess_HOOK. See the last HOOK in its name? You need to target the 'base hook' which is node_add_list. So preprocess that instead of the page.

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.