Skip to main content
  • Guides & Documentation

Knowledgebase

Featured articles, how-to guides and quick tips.

Twig: Get Path to Theme Directory (And it's Images & Assets) in Drupal 8

When theming Drupal 8, it's fairly predictable to assume that at some point you'll need to get the directory of the current theme.

This is useful in situations where you need to include an image stored within the themes images directory within a Twig template.

An example use case could be that you need to reference a logo image, or possibly a static image in the footer.

In situations like this, you won't want to include a hard-coded URL to the image, and neither will you want the ability to manage the image using files or media entities from within the Drupal administration panel.

So it's safe to say that the best bet is to include the reference to such an image directly within your Twig template. Drupal doesn't make this super easy natively, but it's possible with a couple of additional lines of code.

The best bit is that once you've applied these changes within your theme, you'll never have to be concerned with the issue again, if the need arises in future.

It's also entirely possible to reference other kinds of assets in this way — it's not limited to image files.

So for instance, it's also possible (but probably not advisable) to call a JS file, or (more advisable) an SVG file or other similar asset.

First, open up your themes theme.theme (if your theme is named 'example', the file would be called example.theme) file, and add the following hook:

function theme_preprocess(&$variables, $hook) {
    $variables['base_path'] = base_path();
}

Then, in your Twig file, link to your image (or other) file like this:

{{ base_path ~ directory }}/images/file.jpg

Finally, clear your Drupal cache and you'll be all set!