模板賦值
模板賦值
除了系統(tong)變量(liang)和(he)配置參數輸(shu)(shu)(shu)出(chu)無需(xu)賦(fu)值外(wai),其他變量(liang)如果需(xu)要在模(mo)(mo)板(ban)中輸(shu)(shu)(shu)出(chu)必須首先進行模(mo)(mo)板(ban)賦(fu)值操作,綁定數據到(dao)模(mo)(mo)板(ban)輸(shu)(shu)(shu)出(chu)有下(xia)面幾種方式:
| 版本 | 新增功能 |
|---|---|
| 5.0.4 |
增加全局靜態模板賦值方法share |
assign方法
namespace index\app\controller;
class Index extends \think\Controller
{
public function index()
{
// 模(mo)板變量賦(fu)值
$this->assign('name','ThinkPHP');
$this->assign('email','thinkphp@qq.com');
// 或者(zhe)批量賦(fu)值
$this->assign([
'name' => 'ThinkPHP',
'email' => 'thinkphp@qq.com'
]);
// 模板輸出(chu)
return $this->fetch('index');
}
}
傳入參數方法
方法fetch 及 display 均可傳入模(mo)版變量,例如
namespace app\index\controller;
class Index extends \think\Controller
{
public function index()
{
return $this->fetch('index', [
'name' => 'ThinkPHP',
'email' => 'thinkphp@qq.com'
]);
}
}
class Index extends \think\Controller
{
public function index()
{
$content = '{$name}-{$email}';
return $this->display($content, [
'name' => 'ThinkPHP',
'email' => 'thinkphp@qq.com'
]);
}
}
助手函數
如果使用(yong)view助(zhu)手函(han)數渲染輸出的(de)話,可(ke)以使用(yong)下面的(de)方法進行模板(ban)變量賦值(zhi):
return view('index', [
'name' => 'ThinkPHP',
'email' => 'thinkphp@qq.com'
]);
share方法
V5.0.4+開始,支持在(zai)任何地方(fang)使用(yong)靜態方(fang)法(fa)進行模板變量賦值,例如:
think\View::share('name','value');
// 或(huo)者批(pi)量賦值
think\View::share(['name1'=>'value','name2'=>'value2']);
全局靜態(tai)模板(ban)變量(liang)(liang)最終會和前面使用方法賦值的模板(ban)變量(liang)(liang)合并(bing)。
文檔最后更新時間:2018-04-26 10:28:43
未解決你的問題?請到「問答社區」反饋你遇到的問題
