简体   繁体   中英

How to render items with different views in Yii2 ListView?

I need to display the news with different views. Now I use this code for a presentation:

 <?= ListView::widget([
                   'dataProvider' => $dataProvider,
                   'itemView' => '_news',
                   'viewParams' => [
                       'fullView' => true,
                       'context' => 'main-page'
                   ]
               ]);
                ?>

My problem is this: The first 3 news show with large images, the other display with small images. Pagination should work necessarily. See this example 在此处输入图片说明

Please, help me.

Each item view of List view has a variable called $index which can be used to achieve your desired result. In _news.php you can do the following,

if($index < 3)
    $this->render('_news_big', ['model' => $model]);

else
    $this->render('_news_small', ['model' => $model]);

And have the actual code for the big blocks in _news_big.php and the code for small blocks in _news_small.php .

The other way of doing it is to place the code for both the blocks inside _news.php , (although i don't prefer this method)

if($index < 3)
{
    //Code for big block
}
else
{
    //Code for small blocks
}

For more information about itemView, please refer http://www.yiiframework.com/doc-2.0/yii-widgets-listview.html#$itemView-detail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM