Ad

Laravel "top-down" Template Rendering

- 1 answer

I've got a simple problem with Laravel and/or Blade and didn't figure out how to fit this into the Laravel-paradigms:

I have a parent view which should display a list of different child-views. In my current understanding I need to go down to the list-element and "extend" the parent element. But how should I insert the sibling-templates? I need a way to render the templates "top-down" and not "bottom-up".

------ Parent template -----
group.show

    --------- List ---------
    group_assets.type-A.show
    group_assets.type-B.show
    group_assets.type-B.show
    group_assets.type-B.show
    group_assets.type-C.show
    group_assets.type-A.show

My approach was the following:

class GroupController extends Controller {
    ...

    public function show($id){
        $group = Group::find($id);

        $view = view('groups.show', [
            'group' => $group
        ]);


        $groupAssetController = new GroupAssetController();

        foreach($group->assets as $i => $asset){
            $view->with($groupAssetController->show($asset->id));
        }

        return $view;
    }

    ...
}



class GroupAssetController extends Controller{
    ...

    public function show($id){
        $asset = GroupAsset::find($id);

        return view('group_assets.' . $asset->type . '.show', [
            "asset" => $asset
        ]);
    }

    ...
}
Ad

Answer

You can include subviews from within your master view by using the @include directive. First you should eager-load the assets:

class GroupController extends Controller {

    public function show($id) {
        // Eager load assets
        $group = Group::with('assets')->find($id);

        return view('groups.show', [
            'group' => $group
        ]);
    }

}

Then you can include the subviews dynamically and pass the asset model that should be available to each subview:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Master View</title>
</head>
<body>
    {{-- include subviews for each asset --}}

    @foreach($group->assets as $asset)
        @include('group_assets.' . $asset->type . '.show', ['asset' => $asset])
    @endforeach
</body>
</html>
Ad
source: stackoverflow.com
Ad