模板賦值
模板賦值
除了系統(tǒng)變量和配置參數(shù)輸出無(wú)需賦值外,其他變量如果需要在模板中輸出必須首先進(jìn)行模板賦值操作,綁定數(shù)據(jù)到模板輸出有下面幾種方式:
版本 | 新增功能 |
---|---|
5.0.4 |
增加全局靜態(tài)模板賦值方法share |
assign
方法
namespace index\app\controller;
class Index extends \think\Controller
{
public function index()
{
// 模板變量賦值
$this->assign('name','ThinkPHP');
$this->assign('email','thinkphp@qq.com');
// 或者批量賦值
$this->assign([
'name' => 'ThinkPHP',
'email' => 'thinkphp@qq.com'
]);
// 模板輸出
return $this->fetch('index');
}
}
傳入?yún)?shù)方法
方法fetch 及 display 均可傳入模版變量,例如
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'
]);
}
}
助手函數(shù)
如果使用view助手函數(shù)渲染輸出的話,可以使用下面的方法進(jìn)行模板變量賦值:
return view('index', [
'name' => 'ThinkPHP',
'email' => 'thinkphp@qq.com'
]);
share
方法
V5.0.4+
開(kāi)始,支持在任何地方使用靜態(tài)方法進(jìn)行模板變量賦值,例如:
think\View::share('name','value');
// 或者批量賦值
think\View::share(['name1'=>'value','name2'=>'value2']);
全局靜態(tài)模板變量最終會(huì)和前面使用方法賦值的模板變量合并。
文檔最后更新時(shí)間:2018-04-26 10:28:43
未解決你的問(wèn)題?請(qǐng)到「問(wèn)答社區(qū)」反饋你遇到的問(wèn)題