2014-04-09 41 views
2

我想要一个变量传递给我“主人”的布局:Laravel 4 +可变传递掌握布局

//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 ?!?! 
    } 

} 

我想设置一次$ title变量,以及我想要做的时候 - 覆盖它。/

如何做到这一点: 现在我必须在我调用另一个方法每次设置变量?如何只为这个'主'布局设置$ title变量?

Symphony2有前()/()方法之后 - 有什么laravel?

回答

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'; 
+1

好的答案,正是我所期待的。 –