Skip to main content

Adding a global variable to the twig layer on every part of the page in Drupal 8

Member for

2 years 2 months
Submitted by admin on

In Drupal 8 adding a variable so the twig layer can access it on every part of the page can be done by using the template preprocessor, The word template in this function will be replaced by your theme name.

/**
 * Implements hook_preprocess().
 */
function template_preprocess(&$vars) {

  $vars['global_var_name'] = 'This is my var';

}

And then in the twig layer(file) where you need to use the variable.

{{global_var_name}}