1

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

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, privacy policy and cookie policy

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