ThinkPHP筆記15——模板賦值與變數輸出
阿新 • • 發佈:2019-01-24
1.
<?php namespace app\index\controller; use think\Controller; use think\facade\View; class Demo7 extends Controller { public function test1() { //一.直接將內容輸出到頁面,不通過模板 $content = '<h3 style="color:yellow">PHP歡迎你</h3>'; return $this->view->display($content); //推薦該條語句 // return $this->display($content);// return View::display($content); //靜態代理 } public function test2() { /* * 二.使用檢視將資料進行輸出: fetch() 非常重要,貫穿整個開發 * 在模板中輸出資料 * 模板預設的目錄位於當前目錄的view目錄,模板檔案預設位於以當前控制器命名的目錄中 * D:\wamp64\www\thinkphp5.1\tp5.1\application\index\下建立view資料夾 * 然後在D:\wamp64\www\thinkphp5.1\tp5.1\application\index\view下建立* 與當前Demo7.php對應的小寫demo7資料夾,在demo7中建立與Demo7.php中方法對應的 方法名檔案(可以php或html其他) */ //模板變數賦值:assign() //1.普通變數 $this->view->assign('name','like'); $this->view->assign('age','20'); //批量賦值 $this->view->assign([ 'sex'=>'男', 'work'=>'student', ]); //2.陣列 $this->view->assign('goods',[ 'id'=>1, 'name'=>'手機', 'model'=>'iphoneX', 'price'=>8888, ]); //3.物件 $obj = new \stdClass(); //表示當前類來自全域性 $obj->course='PHP'; $obj->teacher='php.cn'; $this->view->assign('info',$obj); //4.常量 define('SITE_NAME','PHP中文網'); //模板自動定位實現輸出D:\wamp64\www\thinkphp5.1\tp5.1\application\index\view\demo7\test2.html return $this->view->fetch(); } public function test3() {} }
2.
{//輸出普通變數} {$name}<br> {$age}<br> {$sex}<br> {$work} <hr> {//輸出陣列} {$goods.id}<br> {$goods.name}<br> {$goods['model']}<br> {$goods['price']}<br> <hr> {//輸出物件} {$info->course}<br> {$info->teacher}<br> <hr> {//輸出常量} {$Think.const.SITE_NAME}<br> <hr> {//輸出PHP原生系統常量} {$Think.const.PHP_VERSION}<br> {$Think.const.PHP_OS}<br> <hr> {//輸出PHP原生系統變數} {$Think.server.php_self}<br> {$Think.server.session.id}<br> {$Think.server.get.name}<br> {$Think.server.post.name}<br> <hr> {//輸出ThinkPHP常量配置} {$Think.config.database.hostname}<br> <hr> {//輸出請求變數--用的比較多} {$Request.get.name}<br> {$Request.param.name}<br> {$Request.path}<br> {$Request.root.true}<br> {$Request.controller}<br> {$Request.action}<br> {$Request.host}<br> {$Request.ip}<br>