回到最上方

文件

樣板

控制器輸出

Laravel 其中一個使用樣板的方法是透過 "控制器 (Controller)" 的 layout,藉由設定在控制器的 layout 屬性值,指定特定的視圖作為預設回傳的回應資料。

在控制器定義 Layout

class UserController extends BaseController {

    /**
     * layout會被用在請求回應中
     */
    protected $layout = 'layouts.master';

    /**
     * 顯示使用者個人檔案
     */
    public function showProfile()
    {
        $this->layout->content = View::make('user.profile');
    }

}

Blade樣板

Blade 是 Laravel 提供的一個簡單且強大的樣板引擎,不同於控制的 Layout,Blade是透過 樣板繼承 (template inheritance)區段 (sections) 去驅動的,所有的 Blade 樣板需使用 .blade.php 作為附檔名。

定義 Blade Layout

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

<html>
    <body>
        @section('sidebar')
            這是主要的 sidebar.
        @show

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

使用 Blade Layout

@extends('layouts.master')

@section('sidebar')
    @parent

    <p>這段會被加到 layouts.master 的 sidebar中</p>
@stop

@section('content')
    <p>這裡是我的內文。</p>
@stop

注意到視圖僅僅覆寫 繼承 (extend) Blade 樣板的 layout 的區段資料 (section),Layout 的內容可以使用 @parent 方法被引用到子視圖區段中,允許你附加 layout 區段資料的內文,像是 sidebar 或是 footer。

其他Blade控制結構

列印資料

Hello, {{ $name }}.

現在的 UNIX 時間戳記是 {{ time() }}.

你可以使用三個大括弧去跳脫輸出的資料:

Hello, {{{ $name }}}.

If 陳述式

@if (count($records) === 1)
    有一筆資料
@elseif (count($records) > 1)
    有多筆資料
@else
    沒有任何資料
@endif

@unless (Auth::check())
    你尚未登入
@endunless

Loops

@for ($i = 0; $i < 10; $i++)
    現在的值是 {{ $i }}
@endfor

@foreach ($users as $user)
    <p>這是使用者 {{ $user->id }}</p>
@endforeach

@while (true)
    <p>我是無限迴圈</p>
@endwhile

包含子視圖

@include('view.name')

顯示語言資訊

@lang('language.line')

@choice('language.line', 1);

註解

{{-- 這個註解將不會產生 HTML 去顯示 --}}

討論