1

来自http://laravel.com/docs/4.2/templates

(控制器)

class UserController extends BaseController {

    /**
     * The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Show the user profile.
     */
    public function showProfile()
    {
        $this->layout->content = View::make('user.profile');
    }

}

(模板)

@extends('layouts.master')

@section('sidebar')


    <p>This is appended to the master sidebar.</p>
@stop

@section('content')
    <p>This is my body content.</p>
@stop

为什么layouts.master需要调用两次?$this->layout需要设置的事实layouts.master和需要传递的事实layouts.master似乎@extends()......多余和不必要的。

4

1 回答 1

5

在您的showProfile()方法中放置以下内容就足够了:

return View::make('user.profile');

代替:

protected $layout = 'layouts.master';

$this->layout->content = View::make('user.profile');

编辑

使用$layout属性的另一种方法有点复杂。

layouts.master模板中你不使用yield('content')但你把{{ $content }}它作为变量,所以文件看起来像这样:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
  test

 {{ $content }}

  test2

{{ $sidebar }}

</body>
</html>

现在您可以像以前一样拥有财产:

protected $layout = 'layouts.master';

您需要使用以下方法设置变量contentsidebar变量:

$this->layout->content = 'this is content';
$this->layout->sidebar = 'this is sidebar';

布局会自动显示

当然,在上述两种情况下,您可以使用使用模板,这样您就可以使用:

$this->layout->content = View::make('content');
$this->layout->sidebar = View::make('sidebar');

并且在这些文件中定义了内容@section,例如:

content.blade.php

this is content

sidebar.blade.php

this is sidebar

输出将是:

test this is content test2 this is sidebar 

这种方法对我来说要复杂得多。我总是使用return View::make('user.profile');并且已经定义了我的模板,就像你在开始时展示的那样(扩展其他模板@section以放置它自己的内容)

于 2014-10-01T21:38:54.270 回答