Drupal - How do I get the base path?

You can use url() to generate a base url to any route in Drupal. You can supply the <front> route which, in effect, will be your base URL.

{{ url('<front>') }}

But, render it first if you're concatenating it:

{{ url('<front>')|render ~ file_url('public://image.jpg') }}

For example:

{{ url('<front>') ~ file_url('public://image.jpg') }}
# Outputs: "Array/sites/all/default/files/image.jpg"

{{ url('<front>')|render ~ file_url('public://image.jpg') }}
# Outputs: "http://example.com/sites/all/default/files/image.jpg"

You almost never need to explicitly build up paths from parts in Drupal 8. I would go with something like this:

function FOO_preprocess_node(&$variables) {
  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];
  $variables['url'] = $node->toUrl('canonical', [
    'absolute' => TRUE,
    'language' => $node->language(),
  ])->toString();
}

In page.html.twig you will have a working {{ base_path }} variable. Why it isn't available in every template, i have no idea. As i think it should be and everything else looks messy, my preferred solution is to do exactly as Drupal does in the preprocess page function for any place i need it.

To make {{ base_path }} available to block templates in a theme named example, add this code to the example.theme file:

/**
 * Implements hook_preprocess_block().
 */
function example_preprocess_block(&$variables) {

  $variables['base_path'] = base_path();
}

As noted in the accepted answer provided by MPD, if getting a node's or other entity's URL there are methods to do it all for you.

However, there are reasons for getting the base_path, such as when displaying images that live in your theme folder. {{ directory }} provides the path to the theme folder, but it leaves off the base path (usually just a / but in order to preserve Drupal's proper functioning from a subdirectory of a domain that shouldn't be hardcoded). On page.html.twig or in any template which has the above preprocesser, this will work for that purpose:

<img src="{{ base_path ~ directory }}/images/nsf1.svg"
     alt="National Science Foundation logo" height="80" width="80" />

And of course Shawn Conn's answer works fine if you can suppress your desire for pretty templates, but i couldn't.

Tags:

Theming