<?php// 视图类namespace phpcn;class view{//约定:控制器方法的模板,就是以控制器为目录名,以方法为文件名protected $controller;protected $action;protected $path;// 模板变量容器protected $data = [];// 初始化时创建模板的路径public function __construct($controller,$action,$path = '/view/'){$this->controller = $controller;$this->action = $action;$this->path = $path;}// 模板赋值:用assign()方法// assign()方法:在thinkphp中,assign()方法用于打印数组,该方法的第一个参数是在模板取值时所使用// 的变量名,第二个参数是要传递的值,语法为“$this->assign('name',$value);”。public function assign($name,$value){// $name 是外部变量在模板文件中的变量// $value 是模板变量的值$this->data[$name] = $value;}// 模板渲染:一般用render()方法// 将模板赋值与模板渲染二合一public function render($path = '' ,$name = null, $value = null){if ($name && $value) $this->assign($name,$value);// 展开模板变量数组extract($this->data);if (empty($path)) {// 按约定规则来生成模板文件的路径并加载它$file = __DIR__ .$this->path . $this->controller . '/' .$this->action . '.php';} else {$file = $path;}// include $file or die('视图不存在);file_exists($file) ? include $file : die('视图不存在');}}// 测试$controller = 'User';$action = 'hello';$view = new View($controller,$action);// 模板赋值:变量$view->assign('username','朱老师');$items = [['name' =>'手机','price' => 2000],['name' =>'电脑','price' => 3800],['name' =>'相机','price' => 1800],];$view->assign('items',$items);// 渲染模板// $view->render();// 渲染,赋值二合一$view->render($path = '','lang',['php','java','python']);
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><h3>User控制器的hello()方法</h3><h3>Hello,<?= $username ?></h3><ul><?php foreach ($items as ['name'=>$name,'price'=>$price]): ?><li><?= $name ?> :<?= $price ?>元</li><?php endforeach ?></ul><ul><?php foreach ($lang as $value): ?><li><?= $value ?></li><?php endforeach ?></ul></body></html>
运行效果:
相关推荐
© 2020 asciim码
人生就是一场修行