首页 > 解决方案 > 如何在 DetailView Yii2 中添加循环?

问题描述

好的,这可能很简单。我想在 Yii2 的 DetailView 中添加循环。
例子 :

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        [
            'attribute' => 'atasan',
            'value' => /*I want to add looping here*/
        ],
    ],
]) ?>


我怎样才能做到这一点?谢谢您的回答 :)

标签: phpyii2

解决方案


由于版本2.0.11 value也可以是匿名函数,因此:

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        [
            'attribute' => 'atasan',
            'value' => function($model) {
                  $example = '';
                  foreach($model->atasan as $atasan) {
                        //here your stuff
                        $example .= 'Oh God, it looped again. '; 
                  }
                  return $example;                // here's returned value
            }
        ],
    ],
]) ?>

请记住,这个匿名函数应该return是一个 value,而不是 echo 或任何东西。


推荐阅读