2

How can I get access to image path (source/url) in twig template of a module?
I try to render an image that's located in my module folder in module template, this image is a static image that's not assigned to a field.
I try several methods to achieve this demands for eg:

<img src="{{ directory }}/image/icons/my-image.svg" />

and below method:

MyModule.module

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

and then in template:

<img src="{{ base_path ~ directory }}image/icons/my-image.svg" />

And i try solution that's written in this article too: Using images in custom module
But both of them refer to my theme directory instead of module directory and seems none of them work in module template.
Thanks for any solution.

1 Answer 1

6

You need to use file_create_url much like Drupal 7 to transform a file path to file url. To get the path to the module, you should use drupal_get_path, combined it could look like this:

function my_module_preprocess(&$variables, $hook) {
  $variables['img_path'] = file_create_url(drupal_get_path('module', 'my_module') . '/image/icons/my-image.svg');
}
1
  • 1
    So in twig, you can use <img src="{{ img_path }}" /> Commented Nov 23, 2020 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.