- 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 underbasic/views
, thatNewsController
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 underbasic/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
isactionItemsList
(the function name hasaction
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!
- Puppet 4 Essentials(Second Edition)
- The DevOps 2.3 Toolkit
- Rake Task Management Essentials
- JavaScript+jQuery開發實戰
- Java編程指南:基礎知識、類庫應用及案例設計
- MariaDB High Performance
- Rust Essentials(Second Edition)
- Java程序設計:原理與范例
- Scala編程實戰(原書第2版)
- ASP.NET開發與應用教程
- 編程與類型系統
- SQL Server實用教程(SQL Server 2008版)
- 21天學通C++(第5版)
- Kotlin開發教程(全2冊)
- 單片機原理及應用技術