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 Mar 25, 2024
1 parent ac1a5af commit d2b55fc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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
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 d2b55fc

Please sign in to comment.