Warm tip: This article is reproduced from serverfault.com, please click

Passing View Variable to Included Layout Template in Laravel 8

发布于 2020-11-28 09:42:32

This is probably something simple, but it's doing my head in.

So, my layout blade template has this:

@include('layouts.partials.sidebar')
  
  {{ $slot }}
  
  @include('layouts.partials.footer')
  @include('layouts.partials.scripts')

I create a view which loads a template. This I assume gets parsed in $slot.

return view('request', [
  'boo' => 'Hoo'
]);

No problems, the page loads and the variable 'boo' is accessible as {{ $boo }} in the 'requests' template.

But my question is, how can I pass the 'boo' variable to an included file in the layout file? In this case the following:

@include('layouts.partials.scripts')

So, in 'layouts.partials.scripts' how can I access {{ $boo }}? At the moment I just get an undefined index error.

Thank you very much for the help.

Questioner
David
Viewed
0
Donkarnash 2020-11-28 18:04:38
@include('layouts.partials.scripts', ['boo' => 'Hoo'])

Laravel docs: https://laravel.com/docs/8.x/blade#including-subviews

If you have a partial like nav or header or sidebar which is a part of the master layout from which you are composing other views and it requires some data which doesn't change from one view to another like navigation links.

Then instead of passing the data from each controller method you can define view composer in a service provider - boot() method

//Service Provider's boot method
public function boot()
{
    View::composer('layouts.partials.sidebar', function ($view) {
    
        //$links = get the data for links

        return $view->with('links', $links);
    });
}

Laravel dos: https://laravel.com/docs/master/views#view-composers