How can I print $base_url in a template?

  • 2
    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
    Commented Jul 28, 2016 at 13:50

2 Answers 2


$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 }}

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 and acknowledge you have read our privacy policy.

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