Render a view inside layout (Undefined variable: dataProvider)

I’m using Yii2 advanced ; I create a controller : CategoryController extends Controller

with function




public function Wdgcategory()

    {

        $dataProvider = new ActiveDataProvider([

            'query' => Category::find(),

        ]);


        return $this->render('/layouts/main', [

            'dataProvider' => $dataProvider,

        ]);

    }

and in my layouts/main

I add the code




<?=

<?= ListView::widget([

	'dataProvider' => $dataProvider,

	'itemOptions' => ['class' => 'item'],

	'itemView' => function ($model, $key, $index, $widget) {

	return '<li>'

	.Html::a(Html::encode($model->category_name),

	['view', 'id' => $model->category_id])

	.'<li>';

	},

]) ?>



But I get error :




PHP Notice – yii\base\ErrorException

Undefined variable: dataProvider



Hi Bynd,

You can not access the variables passed to the view in the layout directly.

Guide > Views > Layouts (https://www.yiiframework.com/doc/guide/2.0/en/structure-views#layouts)

I found solution if someone need it ; I use widgets

my widget :




class CategoriesWidget extends \yii\base\Widget {


    public function run() {

        $dataProvider = new ActiveDataProvider([

            'query' => Category::find(),

        ]);


        return $this->render('categories', [

            'dataProvider' => $dataProvider,

        ]);

    }



and add widget to layout


<?= CategoriesWidget::widget() ?>