Last active
February 8, 2024 11:40
-
-
Save reinis-kinkeris/929e7862d25e14332b821d9ce592090a to your computer and use it in GitHub Desktop.
Drupal 8 - Example of adding dynamic js libraries which require locale
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implements hook_library_info_build(). | |
* | |
* @return array | |
*/ | |
function hook_library_info_build() { | |
$libraries = []; | |
/** @var \Drupal\Core\Language\LanguageManager $language_manager */ | |
$language_manager = \Drupal::languageManager(); | |
/** @var \Drupal\Core\Language\LanguageInterface[] $languages */ | |
$languages = $language_manager->getLanguages(); | |
foreach ($languages as $language) { | |
$language_id = strtolower($language->getId()); | |
$libraries['mymodule.moment_with_locale_' . $language_id] = [ | |
'js' => [ | |
// assuming locale file names are defined same as Drupal langcodes | |
'js/vendor/moment/locale/' . $language_id . '.js' => [], | |
], | |
'dependencies' => [ | |
'mymodule/moment', | |
], | |
]; | |
} | |
return $libraries; | |
} | |
$build['#attached']['library'][] = 'mymodule/moment_with_locale_' . strtolower(\Drupal::languageManager()->getCurrentLanguage()->getId()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment