How to get the base path for your Drupal 8 site in a Twig template
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:
<?php
/**
* Implements hook_preprocess_block().
*/
function example_preprocess_block(&$variables) {
$variables['base_path'] = base_path();
}
?>
Note that 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" />
Comments
Post new comment