Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Allow passing custom attributes for script tags #4

Merged
merged 1 commit into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}