data-* 属性不适用于 Yii 2 中的 Html::a()
data-* attributes do not work with Html::a() in Yii 2
我有以下内容:
Html::a('Link', ['some/route'], [
'class' => 'btn btn-lg btn-primary', // WORKS
'style' => 'padding: 100px;', // WORKS
'data-id' => 123, // DOES NOT WORK
'data' => [
'id' => 123, // DOES NOT WORK
],
]);
根据 docs,Html::a
助手中指定的两个 data-*
属性应该在 HTML 输出中呈现它们各自的属性,但它们没有,并且我不明白为什么。
关于 renderTagAttributes 的 Yii 2 文档也说明了以下内容:
Renders the HTML tag attributes.
Attributes whose values are of boolean type will be treated as boolean
attributes.
Attributes whose values are null will not be rendered.
The values of attributes will be HTML-encoded using encode().
The "data" attribute is specially handled when it is receiving an
array value. In this case, the array will be "expanded" and a list
data attributes will be rendered. For example, if 'data' => ['id' =>
1, 'name' => 'yii'], then this will be rendered: data-id="1"
data-name="yii". Additionally 'data' => ['params' => ['id' => 1,
'name' => 'yii'], 'status' => 'ok'] will be rendered as:
data-params='{"id":1,"name":"yii"}' data-status="ok".
编辑: 我正在尝试在 GridView
列中执行此操作。
好的,因为我在 GridView
列中使用了 Html::a
,您将不得不更改该列的输出格式。 html
不适用于数据属性,因此您需要切换到 raw
:
[
'label' => 'Actions',
'format' => 'raw',
'value' => function($model) {
return Html::a('Link', ['some/route'], [
'class' => 'btn btn-lg btn-primary', // WORKS
'style' => 'padding: 100px;', // WORKS
'data-id' => 123, // WORKS
'data' => [
'id-second' => 123, // WORKS
],
]);
},
]
我有以下内容:
Html::a('Link', ['some/route'], [
'class' => 'btn btn-lg btn-primary', // WORKS
'style' => 'padding: 100px;', // WORKS
'data-id' => 123, // DOES NOT WORK
'data' => [
'id' => 123, // DOES NOT WORK
],
]);
根据 docs,Html::a
助手中指定的两个 data-*
属性应该在 HTML 输出中呈现它们各自的属性,但它们没有,并且我不明白为什么。
关于 renderTagAttributes 的 Yii 2 文档也说明了以下内容:
Renders the HTML tag attributes.
Attributes whose values are of boolean type will be treated as boolean attributes.
Attributes whose values are null will not be rendered.
The values of attributes will be HTML-encoded using encode().
The "data" attribute is specially handled when it is receiving an array value. In this case, the array will be "expanded" and a list data attributes will be rendered. For example, if 'data' => ['id' => 1, 'name' => 'yii'], then this will be rendered: data-id="1" data-name="yii". Additionally 'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok'] will be rendered as: data-params='{"id":1,"name":"yii"}' data-status="ok".
编辑: 我正在尝试在 GridView
列中执行此操作。
好的,因为我在 GridView
列中使用了 Html::a
,您将不得不更改该列的输出格式。 html
不适用于数据属性,因此您需要切换到 raw
:
[
'label' => 'Actions',
'format' => 'raw',
'value' => function($model) {
return Html::a('Link', ['some/route'], [
'class' => 'btn btn-lg btn-primary', // WORKS
'style' => 'padding: 100px;', // WORKS
'data-id' => 123, // WORKS
'data' => [
'id-second' => 123, // WORKS
],
]);
},
]