牛骨文教育服务平台(让学习变的简单)

模板赋值



除了系统变量和配置参数输出无需赋值外,其他变量如果需要在模板中输出必须首先进行模板赋值操作,绑定数据到模板输出有三种方式:

assign方法

namespace indexappcontroller;

class Index extends  hinkController
{
    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');
    }
}

传入参数方法

方法fetch 及 display 均可传入模版变量,例如

namespace appindexcontroller;

class Index extends  hinkController
{
    public function index()
    {
        return $this->fetch('index', [
            'name'  => 'ThinkPHP',
            'email' => 'thinkphp@qq.com'
        ]);
    }
}


class Index extends  hinkController
{
    public function index()
    {
        $content = '{$name}-{$email}';
        return $this->display($content, [
            'name'  => 'ThinkPHP',
            'email' => 'thinkphp@qq.com'
        ]);
    }
}

对象赋值

class Index extends  hinkController
{
    public function index()
    {
        $view = $this->view;
        $view->name     = 'ThinkPHP';
        $view->email    = 'thinkphp@qq.com';
        // 模板输出
        return $view->fetch('index');
    }
}

助手函数

如果使用view助手函数渲染输出的话,可以使用下面的方法进行模板变量赋值:

return view('index', [
    'name'  => 'ThinkPHP',
    'email' => 'thinkphp@qq.com'
]);