Last active
July 6, 2021 22:37
-
-
Save mrkmiller/bff536c5bbfa84fdc4398f95c76cc6e4 to your computer and use it in GitHub Desktop.
Conditionally attach a library in Drupal based on environment
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
| my_lib: | |
| js: | |
| https://path-to-file/my-script.min.js: {type: external, minified: true} | |
| my_lib.test: | |
| js: | |
| https://path-to-file/my-script-test.min.js: {type: external, minified: true} | |
| my_lib.dev: | |
| js: | |
| https://path-to-file/my-script-dev.js: {type: external} |
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
| <?php | |
| // Replace THEMENAME with the name of the theme or module where this code will be added. | |
| /** | |
| * Implements hook_page_attachments_alter(). | |
| */ | |
| function THEMENAME_page_attachments_alter(array &$page) { | |
| // Default to the Dev library. | |
| $lib_name = 'THEMENAME/my_lib.dev'; | |
| // Check if this is Pantheon. | |
| if (isset($_ENV['PANTHEON_ENVIRONMENT'])) { | |
| // Change the library if this is the Live or Test site. | |
| switch ($_ENV['PANTHEON_ENVIRONMENT']) { | |
| case 'live': | |
| $lib_name = 'THEMENAME/my_lib'; | |
| break; | |
| case 'test': | |
| $lib_name = 'THEMENAME/my_lib.test'; | |
| break; | |
| } | |
| } | |
| // Attach the library to the page. | |
| $page['#attached']['library'][] = $lib_name; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment