0

How can I print $base_url in a template?

  • 1
    FWIW, you almost never need to reference the base_url in Drupal 8 directly, especially in template files. In nearly all cases, there are better options. – mpdonadio Jul 28 '16 at 13:50
9

$base_url is not available to template files, but you can easily add it to every template file by implementing hook_template_preprocess_default_variables_alter() in a theme or a module.

function mytheme_template_preprocess_default_variables_alter(&$variables) {
  $variables['base_url'] = $GLOBALS['base_url'];
}

Then, in your template file, you just print its value with the following code.

{{ base_url }}
1

After a little research. You can't do that. You have to use preprocess functions, controllers, or alter hooks to provide $base_url later on in your twig template file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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