批改状态:未批改
老师批语:
<?php
namespace app\index\controller;
use think\facade\View; //引入视图类:并用facade将视图类静态代理:将内部方法全部看到静态进行调用。
use think\Controller;
class Index extends Controller
{
public function index()
{
return '<h4>欢迎来到PHP中文网学习<span>Thinkphp5.1</span>框架</h4>';
}
//模板渲染
public function demo1()
{
$name = 'werm weer';
//使用视图方法:display()不通过模板,直接渲染内容,支持HTML标签(需要引入think\facade\View;)
// return View::display('我的英文名是:<span style="color:red";>'.$name.'</span>');
//简写代码
// return $this->fetch('demo1',['name'=>$name]);
// 使用assign()
// $this->assign('name',$name);
// return $this->fetch();
// 使用助手函数,不依赖任何类
return view('demo1',['name'=>$name]);
}
//模板赋值:
public function demo2()
{
$date = 'week';
//1. assign('模板变量名',值)必须要调用View类,以后我们统一使用Controller来调用
$this->assign('date',$date);
//2.传参方式: fetch()或view()刚才已经演示过了
// return $this->fetch('demo2',['date'=>$date,'salary'=>7000]);
// return view('demo2',['date'=>$date,'salary'=>7000,'sex'=>'男']);
//3.对象赋值:
$this->view->salary = 6000;
$this->view->sex = '男';
return $this->fetch();
}
//模板过滤与替换
public function demo3()
{
//config/template.php: 'tpl_replace_str' => [''=>''],
//建议在控制器使用filter()直接进行过滤替换,更简洁
$this->view->name = 'Chinese website';
$this->view->salary = 9000;
//将模板中的Chinese website替换成:中文网
return $this->filter( function($content) {
return str_replace('Chinese website', 'PHP中文网', $content);
})->fetch();
}
}view目录下的demo1.html
我的英文名是:<span style="color:red";>{$name}</span>
view目录下的demo2.html
我的英文名是:<span style="color:red";>{$date}</span>
<br>
我的工资是:{$salary}
<br>
性别是:{$sex}
view目录下的demo3.html
网站名称是:{$name}
<br>
我的工资是:{$salary}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号