Laravel 4, view composers against @include

2019-04-02 18:10发布

问题:

I noticed if I pass a second parameter to @include like this:

@include('sidebars.pages', array('categories' => Category::all()))

Then it is possible to replicate the concept of render partials within views and render partials within partials like in Rails.

Do I still need view composers with this functionality?

I appreciate any help!

回答1:

While that may be possible it's not the documented use of @include. I'd use caution when doing it like that, and personally, I wouldn't be calling a model within your view. Bind the data you require from your route or controller. Make use of a presenter to perform any presentation logic to keep your views absolutely clean.

@include injects all currently defined variables into the nested partial view. So if you bound all the categories to the parent view, then used @include('sidebars.pages'), that view would also have the categories bound to it.



回答2:

Try View Composers to bind data to views. Works best for partial views

// View Composer Example
View::composer(array('sidebars.pages'), function($view)
{
    $view->with('categories', Categories::all());

});

@include('sidebars.pages')