Skip to content

Commit

Permalink
Add custom attributes to script tags (#20087)
Browse files Browse the repository at this point in the history
  • Loading branch information
skepticspriggan committed Apr 3, 2024
1 parent f7cba1b commit 3071e20
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions framework/helpers/BaseHtml.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
4 changes: 4 additions & 0 deletions framework/web/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ class View extends \yii\base\View
* @see registerJsFile()
*/
public $jsFiles = [];
/**
* @var array the script tag options.
*/
public $scriptOptions = [];

private $_assetManager;

Expand Down
15 changes: 15 additions & 0 deletions tests/framework/helpers/HtmlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,21 @@ public function testScript()
$this->assertEquals("<script type=\"text/js\">{$content}</script>", 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("<script nonce=\"{$nonce}\">{$content}</script>", Html::script($content));
}

public function testCssFile()
{
$this->assertEquals('<link href="http://example.com" rel="stylesheet">', Html::cssFile('http://example.com'));
Expand Down

0 comments on commit 3071e20

Please sign in to comment.