0

As documented here, there are some global variables defined by Drupal. How can I access them in twig?

3 Answers 3

6

These variables are not available to template files, but you can easily add it to every template file by implementing hooks.

You need to prepare variable for twig files. To use the global variables in twig files you need to set it.

Prepares variables for the page template:

You will get details template_preprocess_page.

function template_preprocess_page(&$variables) {
  $variables['base_path'] = base_path();
}
0
0

You can use hook_template_preprocess_default_variables_alter(): https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_template_preprocess_default_variables_alter/8.2.x

This hook allows to add variables to all templates which are passed to twig.

-1

Injecting variables to twig templates from a custom module, for example the 'module path' :

function custom_module_preprocess(&$variables, $hook) {

  $module_handler = Drupal::service('module_handler');
  $path = $module_handler->getModule('amu_http_status_code_display')->getPath();

  if($hook == 'page') {
    $variables['module_path'] = $path;

  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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