From 428eccd9a3d31a86d205bd673edae342047ee357 Mon Sep 17 00:00:00 2001 From: Roman Zimmermann Date: Thu, 2 Nov 2023 08:39:34 +0100 Subject: [PATCH] feat: Allow passing custom attributes for script tags The feature is limited to non-aggregated (preprocess=0) local and external files. --- tests/ModuleTest.php | 32 ++++++++++++++++++++++++++++++++ theming.module | 24 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 tests/ModuleTest.php diff --git a/tests/ModuleTest.php b/tests/ModuleTest.php new file mode 100644 index 0000000..94ac3a0 --- /dev/null +++ b/tests/ModuleTest.php @@ -0,0 +1,32 @@ + tag. + */ + public function testPreRenderScriptsOverridesType() { + $example_url = 'https://example.com/test.js'; + $elements['#items'] = [ + $example_url => [ + 'type' => 'external', + 'defer' => FALSE, + 'attributes' => ['type' => 'module'], + 'data' => $example_url, + ], + ]; + $processed_elements = \theming_pre_render_scripts($elements); + $this->assertEqual([ + 'type' => 'module', + 'src' => $example_url, + ], $processed_elements['scripts'][1]['#attributes']); + } + +} diff --git a/theming.module b/theming.module index 408a437..0ff2800 100644 --- a/theming.module +++ b/theming.module @@ -31,3 +31,27 @@ function theming_theme_registry_alter(&$hooks) { $hook['preprocess functions'] = array_unique($hook['preprocess functions']); } } + +/** + * Implements hook_element_info_alter(). + */ +function theming_element_info_alter(&$info) { + $info['scripts']['#pre_render'] = ['theming_pre_render_scripts']; +} + +/** + * Wrap drupal_pre_render_scripts() to add custom attributes to script tags. + */ +function theming_pre_render_scripts(array $elements) { + $processed_elements = drupal_pre_render_scripts($elements); + foreach (element_children($processed_elements['scripts']) as $index) { + // Skip aggregated scripts. + if (is_string($processed_elements['scripts'][$index])) { + continue; + } + $attributes = &$processed_elements['scripts'][$index]['#attributes']; + $custom_attributes = $elements['#items'][$attributes['src']]['attributes'] ?? []; + $attributes = $custom_attributes + $attributes; + } + return $processed_elements; +}