【问题标题】:redundancy in laravel's templating engine?laravel 模板引擎的冗余?
【发布时间】:2014-11-26 20:44:21
【问题描述】:

来自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-&gt;layout 需要设置为 layouts.master 以及您需要将 layouts.master 传递给 @extends() 的事实似乎......多余且不必要。

【问题讨论】:

标签: php laravel laravel-4 blade laravel-5


【解决方案1】:

在您的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 扩展其他模板以放置自己的内容)

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多