模板变量
模板赋值与变量输出
直接将内容输出到页面,不使用模板
<?php
namespace app\index\controller;
use think\Controller;
//加载静态代理
use think\facade\View;
class Demo7 extends Controller
{
public function test1()
{
$content = "<h3 style='color:red'>PHP中文网欢迎你</h3>";
//return $this->display($content);
//return View::display($content); 静态代理方式
return $this->view->display($content); //推荐
}
}
使用视图(模板)将数据进行输出:fetch
模板变量赋值:
- 输出普通变量
//类文件 Demo7.php
<?php
namespace app\index\controller;
use think\Controller;
//加载静态代理
use think\facade\View;
class Demo7 extends Controller
{
public function test2()
{
//1、普通变量赋值
$this->view->assign('name', 'Tom');
//批量赋值
$this->view->assign([
'age' => 18,
'sex' => '男'
]);
return $this->view->fetch();
}
}
//模板文件 test2.html
<body>
{$name}<br />
{$age}<br />
{$sex}
</body>
- 输出数组
public function test2()
{
//2、数组
$user = [
'id' => '001',
'name' => '张三'
];
$this->view->assign('data', $user);
return $this->view->fetch();
}
<body>
学号:{$data.id}<br />
姓名:{$data['name']}<br />
</body>
- 输出对象
//Demo7.php
public function test2()
{
//3、输出对象
$student = new \app\index\controller\Student('001', '李四');
$this->view->assign('student', $student);
//将变量渲染到模板中
return $this->view->fetch();
}
//Stuent.php
<?php
namespace app\index\controller;
class Student
{
public $id;
public $name;
function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
//test2.html
<body>
学号:{$student->id}<br />
姓名:{$student->name}
</body>
- 输出系统变量
{$Think.server.script_name} // 输出$_SERVER['SCRIPT_NAME']变量
{$Think.session.user_id} // 输出$_SESSION['user_id']变量
{$Think.get.page} // 输出$_GET['page']变量
{$Think.cookie.name} // 输出$_COOKIE['name']变量
- 输出常量
//4、输出常量
define('NAME','ThinkPHP');
return $this->view->fetch();
<body>
{$Think.const.NAME}
</body>
- 使用默认值
可以给 变量 输出提供默认值
{$user.nickname|default="这家伙很懒,什么也没留下"}
- 请求变量
{$Request.get.name} 或
{$Request.param.name}
注:
- 模板变量赋值 assign()函数,可以单个赋值,也可以数组赋值
- 在模板中输出数据:
- 模板默认的目录位于当前模块(index目录)下的view目录
- 模板文件默认位于以当前控制器命名的目录中(就是在view目录中创建一个与当前类同名的目录,在该目录下创建与对应方法同名的模板文件)
- fetch()函数
- 无参时,默认渲染与该函数同名的模板
- 一个参数,一般指定要渲染那个页面。如果模板中存在要输出的变量可以使用assign赋值
- 两个参数,第一个参数指定要渲染那个页面,第二个参数指定要输出的变量,这时可以不需要使用assign函数赋值
- 如果两种情况都存在,首先会渲染fetch函数中的变量,如果某个变量不存在则去assign函数中寻找
//方式一
public function index()
{
$this->view->assign([
'name' => 'zsf456'
]);
return $this->view->fetch('index');
}
//方式二
public function index()
{
return $this->view->fetch('index', ['name' => 'zsf123']);
}
//方式三,name渲染fetch函数中的变量,age渲染assign函数中的变量
public function index()
{
$this->view->assign([
'name' => 'zsf456', 'age' => 11
]);
return $this->view->fetch('index', ['name' => 'zsf123']);
}