Laravel 五 基礎(四)- Blade 簡介

來源:互聯網
上載者:User
Laravel 5 基礎(四)- Blade 簡介

在多個頁面中我們可能包含相同的內容,像是檔案頭,連結的css或者js等。我們可以利用布局檔案完成這個功能。

讓我們建立一個布局檔案,例如 views/layout.blade.php

        Document                @yield('content')    

我們建立了不解的結構,引入了bootstrap,注意 @yield 是blade的布局預留位置,未來我們的頁面內容將填充到這裡,修改 about.blade.php

@extends('layout')@section('content')    

About {{ $first }} {{ $last }}

@stop

上面的代碼錶示我們使用布局檔案 layout.blade.php, 然後在 content 段中新增內容。

在 routes.php 中添加:

Route::get('about', '[email protected]');Route::get('contact', '[email protected]');

在 PagesController.php 中添加:

    public function contact() {        return view('pages.contact');    }

建立視圖 pages/contact.blade.php

@extends('layout')@section('content')    

Contact Me!

@stop

Check it out!

在布局檔案中我們可以添加多個 @yield , 比如在 layout.blade.php 中添加 @yield('footer') :

        Document                @yield('content')        @yield('footer')

比如 contact.blade.php 中有一段指令碼,就可以放在這個段中。

@extends('layout')@section('content')    

Contact Me!

@stop@section('footer') @stop

訪問contact會有對話方塊,而about仍然是普通顯示

  • 使用 @if 進行判斷
@extends('layout')@section('content')    @if ($first = 'Zhang')        

Hello, Zhang

@else

Hello, nobody

@endif@stop

也可以視同 @unless 等同於 if !, 還有 @foreach 等。

    public function about()    {        $people = [            'zhang san',            'li si',            'wang wu'        ];        return view('pages.about', compact('people'));    }
@extends('layout')@section('content')    

Person:

    @foreach($people as $person)
  • {{ $person }}
  • @endforeach
@stop

有一種情況,資料可能來自資料庫,集合可能是空,像是這樣:

$people = [];

處理這種情況,請添加 @if 處理

@extends('layout')@section('content')    @if (count($people))        

Person:

    @foreach($people as $person)
  • {{ $person }}
  • @endforeach
@endif

Other info

@stop

That's better.

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.