With Blade, you can also include partial views (called 'partials') directly into a page like so:
@include('includes.info', ['title' => 'Information Station'])
The code above will include the view at 'views/includes/info.blade.php'. It will also pass in a variable $title
having value 'Information Station'.
In general, an included page will have access to any variable that the calling page has access to. For instance, if we have:
{{$user}} // Outputs 'abc123'
@include('includes.info')
And 'includes/info.blade.php' has the following:
<p>{{$user}} is the current user.</p>
Then the page will render:
abc123
abc123 is the current user.
Include Each
Sometimes, you will want to combine an include
statement with a foreach
statement, and access the variables from within the foreach loop in the include. In this case, use Blade's @each
directive:
@each('includes.job', $jobs, 'job')
The first parameter is the page to include. The second parameter is the array to iterate over. The third parameter is the variable assigned to the elements of the array. The statement above is equivalent to:
@foreach($jobs as $job)
@include('includes.job', ['job' => $job])
@endforeach
You can also pass an optional fourth argument to the @each
directive to specify the view to show when the array is empty.
@each('includes.job', $jobs, 'job', 'includes.jobsEmpty')