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.