1
votes

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.

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?

1
It turned out the solution was to simply rebuild the cache. It's only weird and misleading that defining and changing themename_preprocess_page() was working without rebuilding the cache.Robert Kusznier

1 Answers

1
votes
function themename_preprocess(&$variables) {
    // code
}

Did the trick for me after a cache clear.