将变量从控制器传递到主布局

Hal*_*nex 0 php laravel blade laravel-4

我在views/layouts/main.blade.php中有一个主要布局如何传递我的ListingsController.php中的变量

public function getMain() {
        $uname = Auth::user()->firstname;
        $this->layout->content = View::make('listings/main')->with('name', $uname);
 }
Run Code Online (Sandbox Code Playgroud)

然后我将它添加到listing/main中的main.blade.php

@if(!Auth::check()) 
<h2>Hello, {{ $name }}</h2>
@endif
Run Code Online (Sandbox Code Playgroud)

它工作但我不能将该变量传递给views/layouts/main.blade.php中的mmaster布局我只需要在标题中显示用户的名字.

Ant*_*iro 9

它应该按照它的方式工作,但是......如果你需要将一些东西传播到多个视图,你最好使用View::composer()View::share():

View::share('name', Auth::user()->firstname);
Run Code Online (Sandbox Code Playgroud)

如果只在layout.main上需要它,您可以:

View::composer('layouts.main', function($view)
{
    $view->with('name', Auth::check() ? Auth::user()->firstname : '');
});
Run Code Online (Sandbox Code Playgroud)

如果您在所有视图中都需要它,您可以:

View::composer('*', function($view)
{
    $view->with('name', Auth::check() ? Auth::user()->firstname : '');
});
Run Code Online (Sandbox Code Playgroud)

您甚至可以为此目的创建一个文件,app/composers.php并将其加载到您的app/start/global.php:

require app_path().'/composers.php';
Run Code Online (Sandbox Code Playgroud)