Laravel multiple nested views

2020-07-20 02:15发布

问题:

I'm using laravel layouts and I have a setup like this;

//Controller

public function action_index()
{
    $this->layout->nest('submodule', 'partials.stuff');
    $this->layout->nest('content', 'home.index');
}

// layout

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    @yield('content');
</body>
</html>

// this is the content template

@section('content')
    <div>
        @yield('submodule')
    </div>
@endsection

My question is how can I insert a partial template inside the 'content' section? I also need to pass variables to this second template "submodule".

$this->layout->nest('partial', 'partials.partial');

This doesn't work because it binds the view to layout. Whereas I need to bind it to a section which is defined in the "content" template.

Any ideas?

回答1:

Here is how I fixed the Laravel nested Views problem:

Using this solution you pass data to your main View as well

Solution:

You need to render the partials.stuff inside your home/index.blade.php view and then make a view to render 'content' of 'home/index.blade.php' in your template.php

Use <?php render('partials.stuff') ?>

First make your home/index.blade.php:

<div>
      <?php render('partials.stuff') ?>
</div>

Second render your view -- without any nested 'submodule' call

public function action_index()
{
    $this->layout->nest('content', View::make('home.index'),$data) ;
}

Finally Your template will remain same -- render {{ $content }}

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {{ $content }}
</body>
</html>

Hope this helps you as it has solved my problem :)



回答2:

Here's what you would typically do:

public function action_index()
{
    $this->layout->nest('content', View::make('home.index')->nest('submodule', 'partials.stuff'));
}

And in your template:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    {{ $content }}
</body>
</html>

and your home/index.blade.php:

<div>
     {{ $submodule }}
</div>