How can I get the module path in twig? 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:

&lt;script src="/{{ directory }}/js/script.js"&gt;&lt;/script&gt;


But the directory is returning the theme path NOT the module path. How can I get the module path inside the twig?
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') %}
&lt;script src="/{{ module_path[0] }}/js/script.js"&gt;&lt;/script&gt;


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.