如何在网格视图yii2高级模板中控制模板


How to control template in gridview yii2 advanced template?

我想给 if 条件来控制template attribute中的操作按钮(查看、编辑和删除),并添加新按钮。我有这个代码,但有问题:

[
    'class' => 'yii'grid'ActionColumn',
    'template'=>function ($session){
        if($session->get('userType') != 'admin'){
            '{view}{update}{delete}';
        }else{
            'template' => '{view}{update}{delete}{activate}{deactivate}',
            'buttons' => [
                'deactivate' => function ($url,'backend'models'Document $model) {
                    if($model->Status==1)
                        return Html::a('<span class="glyphicon  glyphicon glyphicon-remove"></span>', $url, [
                            'title' => Yii::t('app', 'deactivate'),
                        ]);
                    },
                'activate' => function ($url, $model) {
                    if($model->Status==0)
                        return Html::a('<span class="glyphicon glyphicon glyphicon-ok"></span>', $url, [
                            'title' => Yii::t('app', 'activate'),
                        ]);
                    },
                ],
            }
        },
    ],

但是我得到了这个错误:

Object of class Closure could not be converted to string

我正在使用会话对象作为函数中的参数。如何解决这个问题,或者检查IF条件的完美方法是什么?

不要使用匿名函数

 'template'=>function ( ... ) {}

但是调用外部函数或通过代码直接使用适当的别名,例如:

'template'=> (if($session->get('userType') != 'admin')) ? '{view}{update}{delete}' : '{view}{update}{delete}{activate}{deactivate}',

public function myTemplate($session){
   ....
   return yourResult;
}

然后

'template'=> myTemplate($session),