问题
There's this <abbr></abbr>
tag in bootstrap that will automatically shows popup of the abbreviated word. I want to insert this tag to a certain header in the gridview with attribute name act
. Here is my code so far.
[
'attribute'=>'act',
'format'=>'raw',
'label'=>'<abbr title="Area Coordinating Team">ACT</abbr>',
'value'=>function($model){
return '<span class="fa fa-thumbs-up text-green"></span>';
}
],
but the output literally shows the whole <abbr title="Area Coordinating Team">ACT</abbr>

回答1:
I already answered that here.
To achieve that, use header
property instead of label
:
[
'attribute' => 'act',
'format' => 'raw',
'header' => '<abbr title="Area Coordinating Team">ACT</abbr>',
'value' => function ($model) {
return '<span class="fa fa-thumbs-up text-green"></span>';
},
],
That way HTML content won't be encoded.
Official docs:
- $header
回答2:
If you would like to have custom HTML and still original sorting functionality, you can create own DataColumn (let's say in common/components), then in grid view set dataColumnClass
:
<?= GridView::widget([
...
'dataColumnClass' => 'common\components\HtmlDataColumn',
'columns' => [
'id',
[
'attribute' => 'title',
'htmlHeader' => 'Some Header<span class="glyphicon glyphicon-ok"></span>',
],
...
My DataColumn:
namespace common\components;
use yii\helpers\Html;
/**
* DataColumn that allows HTML in 'header' yet still appends sorting.
*/
class HtmlDataColumn extends \yii\grid\DataColumn
{
public $htmlHeader = null;
/**
* @inheritdoc
*/
protected function renderHeaderCellContent()
{
if ($this->header !== null || $this->label === null && $this->attribute === null) {
return parent::renderHeaderCellContent();
}
if ($this->htmlHeader !== null) {
$label = $this->htmlHeader;
} else {
$label = $this->getHeaderCellLabel();
if ($this->encodeLabel) {
$label = Html::encode($label);
}
}
if ($this->attribute !== null && $this->enableSorting &&
($sort = $this->grid->dataProvider->getSort()) !== false && $sort->hasAttribute($this->attribute)) {
return $sort->link($this->attribute, array_merge($this->sortLinkOptions, ['label' => $label]));
}
return $label;
}
}
Hope this helps.
来源:https://stackoverflow.com/questions/29962373/how-to-put-custom-html-into-yii2-gridview-header