0

I want to get the human name from the machine name for an extension (i.e. a module or a theme).

I know that I can do this for a module by this call:

$human_name = \Drupal::service('extension.list.module')->getName('automated_cron');

This will return the human name for core Automated Cron module.

To do the same thing for a theme, I can invoke the service 'extension.list.theme'.

Is there something that will provide this information and not care whether the extension is a module or a theme?

In my current implementation, I use this workaround:

$extension_name = 'automated_cron';
if (\Drupal::service('module_handler')->moduleExists($extension_name)) {
  $human_name = \Drupal::service('extension.list.module')->getName($extension_name);
}
else {
  $human_name = \Drupal::service('extension.list.theme')->getName($extension_name);
}
dpm($hunan_name, 'human name');

Is there a simpler way to get the desired result (i.e. without using an if-test)?

1
  • 2
    The module and theme lists are maintained in different service instances. I don't think there is a single service for querying both at the same time.
    – 4uk4
    Commented Oct 11, 2023 at 16:22

1 Answer 1

0

Both extension.list.module and extension.list.theme services extends ExtensionList to get human name.

So you can replace your if statement by this one :

$name = 'automated_cron';
$extension = \Drupal::service('extension.list.module');
$human_name = ($extension->exists($name)) ? $extension->getName($name) : '';

Some useful sources :

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.