From 3071e204cfc3c0beb73ea6394a0cf4bd7567b84b Mon Sep 17 00:00:00 2001 From: Skeptic Spriggan Date: Wed, 3 Apr 2024 14:12:51 +0200 Subject: [PATCH] Add custom attributes to script tags (#20087) --- framework/CHANGELOG.md | 1 + framework/helpers/BaseHtml.php | 5 +++++ framework/web/View.php | 4 ++++ tests/framework/helpers/HtmlTest.php | 15 +++++++++++++++ 4 files changed, 25 insertions(+) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 593400797e3..a348dbf5bf4 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -21,6 +21,7 @@ Yii Framework 2 Change Log - Enh #20032: Added `yii\helpers\BaseStringHelper::mask()` method for string masking with multibyte support (salehhashemi1992) - Enh #20034: Added `yii\helpers\BaseStringHelper::findBetween()` to retrieve a substring that lies between two strings (salehhashemi1992) - Bug #20083: Fix deprecated warning implicit conversion from float (skepticspriggan) +- Enh #20087: Add custom attributes to script tags (skepticspriggan) - Enh #20121: Added `yiisoft/yii2-coding-standards` to composer `require-dev` and lint code to comply with PSR12 (razvanphp) - Enh #20134: Raise minimum `PHP` version to `7.3` (@terabytesoftw) - Bug #20141: Update `ezyang/htmlpurifier` dependency to version `4.17` (@terabytesoftw) diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index e610af6ca1f..0eab768e6e9 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -220,6 +220,11 @@ public static function style($content, $options = []) */ public static function script($content, $options = []) { + $view = Yii::$app->getView(); + if ($view instanceof \yii\web\View && !empty($view->scriptOptions)) { + $options = array_merge($view->scriptOptions, $options); + } + return static::tag('script', $content, $options); } diff --git a/framework/web/View.php b/framework/web/View.php index 21970711a59..52ea7996ca3 100644 --- a/framework/web/View.php +++ b/framework/web/View.php @@ -131,6 +131,10 @@ class View extends \yii\base\View * @see registerJsFile() */ public $jsFiles = []; + /** + * @var array the script tag options. + */ + public $scriptOptions = []; private $_assetManager; diff --git a/tests/framework/helpers/HtmlTest.php b/tests/framework/helpers/HtmlTest.php index c8d36466813..24c8186181b 100644 --- a/tests/framework/helpers/HtmlTest.php +++ b/tests/framework/helpers/HtmlTest.php @@ -90,6 +90,21 @@ public function testScript() $this->assertEquals("", Html::script($content, ['type' => 'text/js'])); } + public function testScriptCustomAttribute() + { + $nonce = Yii::$app->security->generateRandomString(); + $this->mockApplication([ + 'components' => [ + 'view' => [ + 'class' => 'yii\web\View', + 'scriptOptions' => ['nonce' => $nonce], + ], + ], + ]); + $content = 'a <>'; + $this->assertEquals("", Html::script($content)); + } + public function testCssFile() { $this->assertEquals('', Html::cssFile('http://example.com'));