Drupal - How do I get a module path?

To answer the original question (how do I get a module path), and not taking into account the javascript attachment part here is OO friendly solution (without showing the dependency injection itself):

$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler->getModule('my_module')->getPath();

This will give you back the following (of course also depends on how your directory structure looks like)

"modules/custom/my_module"

drupal_get_path is indeed faster to write. However, it calls the same service above statically which makes your code unable to unit test (also not to mention the dependencies of your class are not visible). Long story short: if you choose to make things Quick&Dirty go for drupal_get_path any other cases use the right service yourself with a proper dependency injection.


In Drupal 8 this drupal setting is not available by default. You can check the existing variables by looking for this JSON array on the HTML page:

<script type="application/json" data-drupal-selector="drupal-settings-json">{

To add the module path variable use this code:

$build['#attached']['drupalSettings']['mymodule']['mylib']['path'] = drupal_get_path('module', 'mymodule');

For more info about drupalSettings see:

using {{ twig variables }} inside external jquery

Tags:

Javascript

8