Last Updated: February 25, 2016
·
12.95K
· champjss

Multiple and nested sub-view in Laravel 4

In Laravel 4, as described in the documentation, we can pass a sub-view into a view.

$view = View::make('root.view')
    ->nest('child', 'child.view', $data);

In some trivial case, we may have to nest view inside another nested view, or show many sub-views (that may be generated by code) in the same place. Only nest function is not enough for these cases.

However, without mentioned in the documentation, we can pass an instance of View (or Renderable) as the data of the view with the simple with function. They'll be rendered before being used in the parent view (source).

For example, with our controller function:

public function showNestedViews() {
    $level2ContainerView = View::make('container')
        ->with('content', 'Hello World!');
    $level1ContainerView = View::make('container')
        ->with('content', $level2ContainerView);
    $rootContainerView = View::make('container')
        ->with('content', $level1ContainerView);
    return $rootContainerView;
}

and the container template:

<div>{{ $content }}</div>

will generate this result:

<div>
    <div>
        <div>Hello World!</div>
    <div>
</div>

Even an array of view instances is okay, just use @foreach to iterate through and show each sub-views.

For example, we can generate a list of widgets with this controller function:

public function showWidgets() {
    for ($i = 0; $i < 5; $i++) {
        $widgets[] = View::make('widget');
    }
    $widgetListView = View::make('widget_list')
        ->with('widgets', $widgets);
    return $widgetListView;
}

and this widget_list template:

<ul>
@foreach($widgets as $widget)
    <li>{{ $widget }}</li>
@endforeach
</ul>