Skip to content

Commit

Permalink
Merge pull request #4 from moreonion/script-attributes
Browse files Browse the repository at this point in the history
feat: Allow passing custom attributes for script tags
  • Loading branch information
torotil authored Nov 6, 2023
2 parents 6b79f2c + 428eccd commit c470339
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
32 changes: 32 additions & 0 deletions tests/ModuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Drupal\theming;

use Upal\DrupalUnitTestCase;

/**
* Test hook and callback implementations for the theming module.
*/
class ModuleTest extends DrupalUnitTestCase {

/**
* Test that it’s possible to override the type attribute of a <script> 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']);
}

}
24 changes: 24 additions & 0 deletions theming.module
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit c470339

Please sign in to comment.