我试图将变量传递给我的主人'布局:
//views/dashboard/layouts/master.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
@yield('site.body');
{{{ isset($test) ? $title:'Test no exists :) ' }}}
</body>
</html>
现在在我的DashboardController中:
class DashboardController extends BaseController
{
public $layout = "dashboard.layouts.master";
// this throw error : Cannot call constructor
//public function __construct()
//{
// parent::__construct();
// $this->layout->title = 'cry...';
//}
// this throw error : Attempt to assign property of non-object
// and I understand it, coz $layout isn't an object
//public function __construct()
//{
// $this->layout->title = 'cry...';
//}
public function action_doIndex()
{
$this->layout->title = 'this is short title';
$this->layout->body = View::make('dashboard.index');
}
public function action_doLogin()
{
//$this->layout->title = 'this is short title'; // AGAIN ???
$this->layout->body = View::make('dashboard.forms.login');
}
public function action_doN()
{
// $this->layout->title = 'this is short title'; // AND OVER AGAIN ?!?!
}
}
我想只设置ONCE $ title变量,当我想要它时 - 覆盖它。 现在我每次调用另一个方法时都必须设置变量:/
怎么做?如何为此&#39; master&#39;设置$ title变量仅ONCE布局??
Symphony2有before()/ after()方法 - laravel得到了什么?
答案 0 :(得分:8)
您可以使用View::composer()
或View::share()
将“变量”传递给您的观看次数:
public function __construct()
{
View::share('title', 'cry...');
}
这是作曲家:
View::composer('layouts.master', function($view)
{
$view->with('name', Auth::check() ? Auth::user()->firstname : '');
});
如果您在所有观看中都需要它,您可以:
View::composer('*', function($view)
{
$view->with('name', Auth::check() ? Auth::user()->firstname : '');
});
您甚至可以为此目的创建文件,例如app/composers.php
,并将其加载到app/start/global.php
中:
require app_path().'/composers.php';