laravel模板引擎的冗余?

neu*_*ert 1 php laravel blade laravel-4 laravel-5

来自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');
    }

}
Run Code Online (Sandbox Code Playgroud)

(模板)

@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
Run Code Online (Sandbox Code Playgroud)

为什么layouts.master需要被调用两次?这个事实$this->layout需要被设置为layouts.master和你需要通过事实layouts.master@extends()似乎...多余的和不必要的.

Mar*_*łek 5

你的showProfile()方法就足够了:

return View::make('user.profile');
Run Code Online (Sandbox Code Playgroud)

代替:

protected $layout = 'layouts.master';
Run Code Online (Sandbox Code Playgroud)

$this->layout->content = View::make('user.profile');
Run Code Online (Sandbox Code Playgroud)

编辑

使用$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>
Run Code Online (Sandbox Code Playgroud)

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

protected $layout = 'layouts.master';
Run Code Online (Sandbox Code Playgroud)

你需要的是使用以下方法设置内容contentsidebar变量:

$this->layout->content = 'this is content';
$this->layout->sidebar = 'this is sidebar';
Run Code Online (Sandbox Code Playgroud)

布局将自动显示

当然,在上述2个案例中,您可以使用使用模板,以便您可以使用:

$this->layout->content = View::make('content');
$this->layout->sidebar = View::make('sidebar');
Run Code Online (Sandbox Code Playgroud)

并且在那些文件定义的内容中没有@section例如:

content.blade.php

this is content
Run Code Online (Sandbox Code Playgroud)

sidebar.blade.php

this is sidebar
Run Code Online (Sandbox Code Playgroud)

输出将是:

test this is content test2 this is sidebar 
Run Code Online (Sandbox Code Playgroud)

这种方法对我来说要复杂得多.我总是使用return View::make('user.profile');并定义了我在开头展示的模板(扩展其他模板@section以放置自己的内容)