Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing additional variable to partial using @each in blade

From the documentation, only 4 parameters can be passed to @each. I don't think that using @include will help. Code is below

@each('partials.nav.categories', $groupCategories, 'parent')

I need to send through an additional variable for use in the partial partials.nav.categories. This variable is not contained within the $groupCategories array.

Is there any way to send this additional variable through or do I have to append it to each item in the partials.nav.categories array?

Thanks

like image 564
Muhaimin Avatar asked Dec 31 '15 07:12

Muhaimin


2 Answers

You can share variable from your controller view()->share('key', 'value'); That's value will be available across all of your views.

Or, you can create view composers exactly for this view.

public function yourmethod()
{
   view()->composer('partials.nav.categories', function($view) {
      $view->with('var', 'value');
   });

   return view('path.to.view', ['groupCategories' => $categories]);
}

And $var will be available only in partials.nav.categories view.

like image 103
xAoc Avatar answered Oct 10 '22 23:10

xAoc


I think you are right. Append data to $groupCategories is the right way. As per documentation, The fourth param is what will be displayed if the $groupCategories is empty. You can either pass a view template, which will be shown only once, or any text prepended with raw| will be displayed as is.

General format:

@each('viewfile-to-render', $data, 'variablename','optional-empty-viewfile')

The first argument is the template to render. This will usually be a partial, like your nameofyourblade.blade.php.

The second one is the iterable dataset, in your case $groupCategories.

The Third is the variable name the elements will use when being iterated upon. For example, in foreach ($data as $element), this argument would be element (without the $).

The fourth argument is an optional one – it’s the name of the template file which should be rendered when the second argument ($data) is empty, i.e. has nothing to iterate over. If we apply all this to our case, we can replace this entire block:

@if (count($groupCategories) > 0)
    <ul>
    @foreach ($groupCategories as $parent)
        @include('partials.nav.categories', $parent)
    @endforeach
    </ul>
@else
    @include('partials.group-none')
@endif

with

@each('partials.nav.categories', $groupCategories, 'parent', 'partials.group-none')
like image 22
Ravi Avatar answered Oct 10 '22 23:10

Ravi