视图–模板赋值和模板渲染
在这里插入图片描述
模板赋值(assign方法)
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
//模板给变量赋值
$name='今天的天气真好';
$email='tianqi@qq.com';
$this->assign('name',$name);
$this->assign('email',$email);
/*或者批量赋值
$this->assign([
'name'=>$name,
'email'=>$email
]);
*/
}
}
模板渲染(fetch)
若使用使用return $this->fetch();
,或报错,因为没有视图
so:
先在Index目录下建议一个view文件夹,再在view文件夹下加一个index文件夹,再在此index目录下建立index.html,和test.html,
再建立一个user文件夹,在里面建立个user.html(后面要用到)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
出去玩呀。
</body>
</html>
index.php(controller下的)
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
return this->fetch();
}
}
输出:
现在想传值,把controller的index.php下的index方法下的name
和email输出
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
出去玩呀。<br/>
{$name}<br/>
{$email}<br/>
</body>
</html>
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
//模板给变量赋值
$name='今天的天气真好';
$email='tianqi@qq.com';
$this->assign('name',$name);
$this->assign('email',$email);
/*或者批量赋值
$this->assign([
'name'=>$name,
'email'=>$email
]);
*/
return $this->fetch();
}
}
访问http://localhost:8090/tp5/public/index/index/index.html
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
这是我测试的内容,你猜会不会出现!
</body>
</html>
controller下的Index.php:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
return this->fetch('test');
//test.html模板的输出
}
}
结果:
user目录下的user.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
我这是在做跨模块调用的测试
</body>
</html>
controller下的Index.php:
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
return this->fetch('user/user');
//跨模板调用的输出
}
}
传入参数方法
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
return $this->fetch('index',[
'name'=>'thinkphp',
'email'=>'thinkphp@qq.com'
]);
}
}//就不用assign了
结果:
助手函数
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;
class Index extends Controller
{
public function index()
{
return view('index',[
'name'=>'thinkphp',
'email'=>'thinkphp@qq.com'
]);
}
}//就不用assign了
答案与上面一样