Laravel“自上而下”模板渲染

时间:2016-01-02 23:06:29

标签: php laravel blade

我对Laravel和/或Blade有一个简单的问题,并没有弄清楚如何将其纳入Laravel范例:

我有一个父视图,它应该显示不同子视图的列表。在我目前的理解中,我需要转到list-element并“扩展”父元素。但是我应该如何插入兄弟模板?我需要一种方法来渲染模板“自上而下”而不是“自下而上”。

------ 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

我的方法如下:

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
        ]);
    }

    ...
}

1 个答案:

答案 0 :(得分:1)

您可以使用@include指令在主视图中包含子视图。首先,你应该急于加载资产:

class GroupController extends Controller {

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

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

}

然后,您可以动态地包含子视图,并传递应该对每个子视图可用的资产模型:

<!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>