# 4.4 视图

视图是MVC模式中的一部分,它代表数据到终端用户展示逻辑，视图文件为PHP脚本，主要包含HTML代码和展示类PHP代码。MSF框架整合了第三方的模板引擎[plates](https://github.com/pinguo/plates),并修改了部分源码。

## 使用视图

```php
<?php
/**
 * 示例控制器
 *
 * @author camera360_server@camera360.com
 * @copyright Chengdu pinguo Technology Co.,Ltd.
 */

namespace App\Controllers;

use PG\MSF\Controllers\Controller;
use App\Models\Demo as DemoModel;

class Demo extends Controller
{
    // 略...
    public function actionTplView()
    {
        $data = [
            'title'    => 'MSF Demo View',
            'friends'  => [
                [
                    'name' => 'Rango',
                ],
                [
                    'name' => '鸟哥',
                ],
                [
                    'name' => '小马哥',
                ],
            ]
        ];
        $this->outputView($data);
    }
}
```

示例代码:

[./php-msf-demo/app/Controllers/Demo.php](https://github.com/pinguo/php-msf-demo/blob/master/app/Controllers/Demo.php)

- Controller::outputView($data, $view = null)

加载视图文件,并渲染$data数据

`$data`传递到视图文件的数据,为一个关联数组

`$view`视图文件名称,是相对`app/Views`或者`php-msf/src/Views`的文件名,注意不需要写`.php`的后缀

加载的视图文件为[./app/Views/Demo/TplView.php](https://github.com/pinguo/php-msf-demo/blob/master/app/Views/Demo/TplView.php),即:

```php
<h1><?=$this->e($title)?></h1>
<h2>Friends</h2>
<ul>
    <?php foreach($friends as $friend): ?>
        <li>
            <?=$this->e($friend['name'])?>
        </li>
    <?php endforeach ?>
</ul>
```

## 视图加载策略

1. 默认情况下框架会根据请求的控制器名和方法名自动加载视图文件,比如:

[http://127.0.0.1:8000/Demo/TplView](http://127.0.0.1:8000/Demo/TplView)

这样的URL会自动首先加载的视图文件为`app/Views/Demo/TplView.php`,如果失败,会继续加载`php-msf/src/Views/Demo/TplView.php`,如果还是失败,则会抛出异常。

2. 如果传递了outputView()方法的第二个参数,则会根据$view来加载视图文件,策略同1,先加载app下面的视图,如果未找到则加载框架内置的视图文件

## 模板语法

更多的模板方法,请参考[plates docs](https://github.com/pinguo/plates/tree/master/docs)

# links
  * [目录](../README.md)
  * 上一节: [模型](4.3-模型.md)
  * 下一节: [同步任务](4.5-同步任务.md)