Laravel:如何将变量传递给我的基本布局

Red*_*ube 4 layout laravel blade

我正在尝试将变量传递给我的基本布局。这是因为我在所有页面中都需要它。我认为在我的 BaseController 上写类似的东西

protected function setupLayout()
{
    if ( ! is_null($this->layout))
    {
        $footertext = MyText::where('status', 1);
        $this->layout = View::make($this->layout, ['footertext' =>$footertext ]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为在我的 main.blade.php 上写类似的东西是可行的。

 {{ $footertext }}.
Run Code Online (Sandbox Code Playgroud)

相反,我有这个错误,

未定义变量:footertext

经过两个小时的环顾……我没有找到任何解决方案。欢迎任何帮助。

Thi*_*lho 5

不久前,我也在尝试做同样的事情。

如果您使用的是 Laravel 5,您可以在里面编辑 AppServiceProvider.phpapp/Providers并为此布局注册一个提供程序,例如:

public function boot()
{
  view()->composer('my.layout', function($view) {
    $myvar = 'test';
    $view->with('data', array('myvar' => $myvar));
  });
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您使用的是 Laravel 4,我认为它更简单。在app/filters.php

View::composer('my.layout', function ($view) {
  $view->with('variable', $variable);
});
Run Code Online (Sandbox Code Playgroud)

在这两种方式中,您传递的任何变量都可用于扩展主模板的所有模板。

参考:

https://laracasts.com/discuss/channels/general-discussion/laravel-5-pass-variables-to-master-template https://coderwall.com/p/kqxdug/share-a-variable-across-views -in-laravel?p=1&q=author%3Aeuantor