10

I'm creating a module in Drupal 8 and I need to define a relative path to mymodule to pass it on a JavaScript file like this.

$scope.getPlatformIcon = function (_platform) {
     var modulePath = "/modules/mymodule"
     switch (_platform) {
         case "youtube":
         case "twitter":
         case "instagram":
         case "facebook":
             return modulePath+"/img/"+_platform+".png";
     }
     return false;
};

In Drupal 7 I could use the following.

var modulePath = Drupal.settings.mymodule.basePath;

For the Drupal 8 root directory, I could use the following.

drupalSettings.path.baseUrl

I didn't find how to get the module path.

How can I do it with Drupal 8?

7

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

| improve this answer | |
17

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.

| improve this answer | |
  • To get the absolute file system path: \Drupal::service('file_system')->realpath(\Drupal::service('module_handler')->getModule('my_module')->getPath()) – leymannx Nov 19 at 18:34

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.