0

I want to set few global variables which I need to be available in all my theme's Twig templates in Drupal 8.

Drupal 7 documentation mentions preprocess function:

themeName_preprocess This one is named after the theme itself. Applies to all hooks.

So I added the function below to my themename.theme file, but the variables aren't set.

function themename_preprocess(&$variables) {
  $theme_path = $variables['base_path'] . $variables['directory'];
  $variables['theme_path'] = $theme_path;
  $variables['images_path'] = $theme_path . "/images/";
  $variables['templates_path'] = $theme_path . "/templates/";
}

When instead of defining themename_preprocess I define themename_preprocess_page (below) the variables are properly defined and available in page.html.twig template. I also tried defining template_preprocess(), but got error PHP Fatal error: Cannot redeclare template_preprocess() (previously declared in /home/robert/programming/dns-drupal/core/includes/theme.inc:1202).

function themename_preprocess_page(&$variables) {
  $theme_path = $variables['base_path'] . $variables['directory'];
  $variables['theme_path'] = $theme_path;
  $variables['images_path'] = $theme_path . "/images/";
  $variables['templates_path'] = $theme_path . "/templates/";
}

But I want the variables to be available in all templates instead of only page.html.twig. How can I do that?

  • 2
    hook_preprocess hasn't gone anywhere, that should work. Have you rebuilt cache? – Clive Jul 19 '17 at 7:54
  • @Clive: Yeah, it works after rebuilding the cache. Thanks! Only weird that themename_preprocess_page() was working without rebuilding the cache. That was totally misleading - I was sure that themename_preprocess() is simply not working at all. – Robert Kusznier Jul 19 '17 at 7:57

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.