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

3

我有一个位于 views/layouts/main.blade.php 的主布局。 如何传递 ListingsController.php 中的变量?

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

然后我将其添加到位于列表/主目录中的main.blade.php文件中。
@if(!Auth::check()) 
<h2>Hello, {{ $name }}</h2>
@endif

它可以工作,但是我无法将该变量传递到views/layouts/main.blade.php中的主布局。我只需要在标题中显示用户的名字。

3个回答

12

它应该按照它的方式工作,但是......如果您需要将某些内容传递到多个视图中,最好使用View::composer()View::share()

View::share('name', Auth::user()->firstname);

如果你只需要在你的layout.main上使用它,你可以:

View::composer('layouts.main', 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';

我将第二个片段添加到我的ListingsController的构造函数中,它在所有“Listing”页面上都可用,但当我转到用户/仪表板时,会出现“找不到变量”的错误。我尝试了第二种方法来创建一个文件并在global.php中加载它,但是这也没有起作用,出现相同的错误。 - Halnex
我也将其添加到了 UsersController.php 中,现在它可以在所有 users/* 上使用,但我认为这并不实际。 - Halnex
这是我的视图现在在列表中的构造函数View::composer('*', function($view)
{
$view->with('name', Auth::user()->firstname);
}); 但我仍然得到相同的错误。
- Halnex
我觉得它起作用了。我重新访问了我刚创建的composers.php文件,发现里面有个错别字。非常感谢你。 - Halnex
你应该使用服务提供者。 - Adam Kozlowski
显示剩余2条评论

2

为此,请使用专门的类。

首先:

// app/Providers/AppServiceProvider.php
public function boot()
{
    view()->composer('layouts.master', 'App\Http\Composers\MasterComposer');
}

然后:

// app/Http/Composers/MasterComposer.php
use Illuminate\Contracts\View\View;

class MasterComposer {

    public function compose(View $view)
    {
        $view->with('variable', 'myvariable');
    }
}

记得注册服务提供者。

更多信息:https://laracasts.com/series/laravel-5-fundamentals/episodes/25


0
$this->data['uname'] = 'some_username';
return View::make('dashboard.home', $this->data);

编辑:

<?php 
class BaseController extends Controller {

    /**
     * Setup the layout used by the controller.
     *
     * @return void
     */
        protected $layout = 'layouts.front';

    protected function setupLayout()
    {
        if ( ! is_null($this->layout))
        {
               $this->data['sidewide_var'] = 'This will be shown on every page';
           $this->layout = View::make($this->layout, $this->data);
        }
    }

}

_

<?php 
class BlogController extends BaseController {
    public function getPost($id)
    {
      $this->data['title'] = 'Post title'; //this will exist on only this page, but can be used in layouts/front.blade.php (for example)
      return View::make('blog.single_post', $this->data);
    }
}

这是我使用控制器的方式。 $sidewide_var和$title都可以在布局或视图中使用。


1
也许您可以添加更多的信息?目前您的帖子相当令人困惑。 - Arend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接