官术网_书友最值得收藏!

  • Yii2 By Example
  • Fabrizio Caldarelli
  • 357字
  • 2021-07-16 19:38:55

Creating a view to display a news list

Now, we will create a simple news list in a view named itemsList. We will point to this view from NewsController, so we have to:

  • Create a news folder under basic/views, that NewsController will use as the base folder to search for the views to be rendered (according to the view names' rules explained in the previous chapter)
  • Create an itemsList.php file under basic/views/news

Now, open basic/views/news/itemsList.php, create an array with a list of data and display the output with a simple table of items:

<?php
    $newsList = [
        [ 'title' => 'First World War', 'date' => '1914-07-28' ],
        [ 'title' => 'Second World War', 'date' => '1939-09-01' ],
        [ 'title' => 'First man on the moon', 'date' => '1969-07-20' ]
    ];
?>

<table>
    <tr>
        <th>Title</th>
        <th>Date</th>
    </tr>
    <?php foreach($newsList as $item) { ?>
    <tr>
        <td><?php echo $item['title'] ?></td>
        <td><?php echo $item['date'] ?></td>
    </tr>
    <?php } ?>
</table>

Then, we need to create an action provided by a function named actionItemsList that will be rendered by http://hostname/basic/web/index.php?r=news/items-list.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Note

Pay attention to names for routes, controllers, and actions:

  • The route for this action is news/items-list (lowercase and words separated by dashes);
  • The controller class name is NewsController (uppercase with the word Controller in the end);
  • The action function name in NewsController is actionItemsList (the function name has action word as prefix, dashes in the route are removed, and the first letter of each word is in uppercase);

The function to append in the NewsController class is as follows:

public function actionItemsList()
{
     return $this->render('itemsList');
}

The render() method that belongs to \yii\web\Controller, displays in the layout content of the view passed as the first parameter. When the framework is looking for the view, it will append .php extension to the name passed as the first parameter of the render() method and it will look for it in basic/view/news. The last member of the path is the name that is calling the render() method.

Now, we can point to http://hostname/basic/web/index.php?r=news/items-list, to see our beautiful table!

主站蜘蛛池模板: 湄潭县| 上高县| 孙吴县| 宜黄县| 丹巴县| 农安县| 徐闻县| 望谟县| 定兴县| 舞阳县| 安顺市| 盐边县| 凤山市| 高邑县| 绍兴县| 安仁县| 突泉县| 吉林省| 商丘市| 龙山县| 望奎县| 北辰区| 满城县| 鹤庆县| 宁南县| 桑植县| 阿尔山市| 潞西市| 安图县| 石河子市| 大足县| 柳江县| 牡丹江市| 湘乡市| 固原市| 建昌县| 全州县| 施秉县| 兴隆县| 长葛市| 屯留县|