如何将自定义HTML放入Yii2 GridView标头?

时间:2015-04-30 08:09:25

标签: html gridview yii2 formatting yii2-advanced-app

引导程序中的这个<abbr></abbr>标记会自动显示缩写词的弹出窗口。我想将此标记插入到gridview中具有属性名称act的特定标题。到目前为止,这是我的代码。

        [
            '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>';
            }
        ],

但输出字面上显示整个<abbr title="Area Coordinating Team">ACT</abbr>

enter image description here

2 个答案:

答案 0 :(得分:3)

使用:'encodeLabel'=>否,

[
  'attribute'=>'act',
  'format'=>'raw',
  'label'=>'<abbr title="Area Coordinating Team">ACT</abbr>',
  'encodeLabel' => false,
  'value'=>function($model){
      return '<span class="fa fa-thumbs-up text-green"></span>';
  }
],

答案 1 :(得分:1)

如果您想拥有自定义HTML和原始排序功能,您可以创建自己的DataColumn(比如说在common / components中),然后在网格视图集dataColumnClass中创建:

<?= GridView::widget([
    ...
    'dataColumnClass' => 'common\components\HtmlDataColumn',
    'columns' => [
        'id',
        [
            'attribute' => 'title',
            'htmlHeader' => 'Some Header<span class="glyphicon glyphicon-ok"></span>',
        ],
        ...

我的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;
    }
}

希望这有帮助。