0

I have a module and created twig templates there. I just followed the documentation here: https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-for-custom-module

I want to include a JS file from the twig. And the JS file is located inside the module folder. I have this code in the twig:

<script src="/{{ directory }}/js/script.js"></script>

But the directory is returning the theme path NOT the module path. How can I get the module path inside the twig?

  • 2
    The Drupal 8 way is to define a library and then attach the library with {{ attach_library('module-name/library-name') }} read the docs for more info. – No Sssweat Aug 28 at 6:57
  • @Jdrupal, this is not a duplicate because I am asking how to get the module path from the twig file. NOT php – aceraven777 Aug 28 at 7:11
  • 1
    As @NoSssweat says the correct way is to create a library and attach it in twig. – Jdrupal Aug 28 at 7:13
  • 1
    @aceraven777 The principle is the same as in the duplicate; the variable you need isn’t available, you have to implement a preprocess hook and make it available via PHP. But as others have said, this is what libraries are for, you shouldn’t need to build a path to an asset yourself – Clive Aug 28 at 7:19
  • 1
    Possible duplicate of get path to image (src) from twig template – leymannx Aug 28 at 13:22
0

There is a solution that can work for your problem without going into php and this solution will work only in case if twig template is under module directory.

Suppose my module structure is like below:

  • modules
    • custom_module
      • templates
        • my-template.html.twig
      • js
        • script.js

To include script.js in my-template.html.twig file. Use below code in twig file -

{% set module_path = _self|split('/templates') %}
<script src="/{{ module_path[0] }}/js/script.js"></script>

In above script _self returns the path upto twig file and split('/templates') splits the string from /templates AND

module_path[0] = /modules/custom_module/ 
module_path[1] = /my-template.html.twig

However, this is not the appropriate way. This is only a solution for your problem. Appropriate way is to set module path in a variable in preprocess hook and use that variable in twig.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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