User login

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:

     * 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" />
Searched words: 
Drupal 8 Twig path to theme images drupal 8 twig site base path


Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.