Robert Kusznier
Robert Kusznier

Reputation: 6921

How to set variable for all theme templates in Drupal 8?

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?

Upvotes: 1

Views: 1858

Answers (1)

hipertom
hipertom

Reputation: 11

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

Did the trick for me after a cache clear.

Upvotes: 1

Related Questions