1. 程式人生 > >ThinkPHP5.1模板賦值和輸出

ThinkPHP5.1模板賦值和輸出

<?php

//index/controller/Demo1.php

namespace app\index\controller;
use think\Controller;
use think\facade\View;
class Demo1 extends Controller
{


public function index()
{
//直接輸出內容到頁面,不通過模板
$content = '<h3>微語錄www.top789.cn</h3>';
// return $this->display($content);
return $this->view->display($content);//推薦
// return View::display($content);
}
//使用檢視輸出
public function test()
{
//1、普通變數
$this->view->assign('name','Sam');
$this->view->assign('age','99');
//批量
$this->view->assign(['sex'=>'男','salary'=>'9999']);
//2、陣列
$this->view->assign('arr',[
'id'=>'1',
'name'=>'SamC',
'sex'=>'男',
]);
//3、物件
$obj=new \stdClass();
$obj->title='手機';
$obj->price='價格';
$this->view->assign('info',$obj);
//常量
define('SITE_NAME', '微語錄');


return $this->view->fetch();


}
}


---------對應的模板index/view/demo1/test.html


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試</title>
</head>
<body>
{$name}<br />
{$age}<br />
{$sex}<br />
<hr>
{//輸出陣列}
{$arr.id}
{$arr.name}
{$arr['sex']}
<hr>
{//輸出物件}
{$info->title}
{$info->price}
<hr>
{//輸出常量}
{$Think.const.SITE_NAME}
<hr>
{//輸出php系統常量}
{$Think.const.PHP_VERSION}
{$Think.const.PHP_OS}
<hr>
{//輸出系統變數}
{$Think.server.php_self}
{$Think.server.get.name}
<hr>
{//輸出系統配置裡引數}
{$Think.config.database.hostname}
<hr>
{//獲取請求變數}
{$Request.get.title}<br />
{$Request.param.title}<br />
{$Request.path}<br />
{$Request.root}<br />
{$Request.root.true}<br />
{$Request.action}<br />
</body>

</html>

---------------

public function local($tag)
{
  if ($tag=='go') {
            //設定成功後跳轉頁面的地址,預設的返回頁面是$_SERVER['HTTP_REFERER']
            $this->success('操作成功', 'Index/index');
        } else {
            //錯誤頁面的預設跳轉頁面是返回前一頁,通常不需要設定
            $this->error('操作失敗');
        }


}