2014-04-09 81 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

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