代码改变世界

laravel 模板 blade

2014-08-06 14:14  youxin  阅读(1165)  评论(0编辑  收藏  举报

控制器布局

在Laravel框架中使用模板的一种方法就是通过控制器布局。通过在控制器中指定 layout 属性,对应的视图会被创建并且作为请求的默认返回数据。

在控制器中定义一个布局

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

}

Blade模板

Blade是Laravel框架下的一种简单又强大的模板引擎。 不同于控制器布局,Blade模板引擎由模板继承和模板片段驱动。所有的Blade模板文件必须使用Blade .blade.php 文件扩展名。

定义一个Blade布局

<!-- Stored in app/views/layouts/master.blade.php -->

<html>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

使用一个Blade布局 (文件名.blade.php

@extends('layouts.master')

@section('sidebar')
    @parent

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

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

(渲染时直接接文件名,不要blade)

注意一个Blade布局的扩展视图简单地在布局中替换了模板片段。通过在模板片段中使用 @parent 指令,布局的内容可以被包含在一个子视图中,这样你就可以在布局片段中添加诸如侧边栏、底部信息的内容。

Sometimes, such as when you are not sure if a section has been defined, you may wish to pass a default value to the@yield directive. You may pass the default value as the second argument:

@yield('section', 'Default Content');
更多:
http://v4.golaravel.com/docs/4.1/templates#controller-layouts