Skip to content

Instantly share code, notes, and snippets.

@mrkmiller
Last active July 6, 2021 22:37
Show Gist options
  • Select an option

  • Save mrkmiller/bff536c5bbfa84fdc4398f95c76cc6e4 to your computer and use it in GitHub Desktop.

Select an option

Save mrkmiller/bff536c5bbfa84fdc4398f95c76cc6e4 to your computer and use it in GitHub Desktop.
Conditionally attach a library in Drupal based on environment
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}
<?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