首頁  >  文章  >  後端開發  >  Laravel 5 基礎(四)- Blade 簡介

Laravel 5 基礎(四)- Blade 簡介

WBOY
WBOY原創
2016-08-08 09:26:55970瀏覽

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

讓我們新建一個佈局文件,例如 views/layout.blade.php

<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html></code>

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

<code>@extends('layout')

@section('content')
    
<h1>About {{ $first }} {{ $last }}</h1>

@stop</code>

上面的程式碼表示我們使用版面配置檔案 layout.blade.php, 然後在 content 段中加入內容。

routes.php 中加入:

<code>Route::get('about', 'PagesController@about');
Route::get('contact', 'PagesController@contact');</code>

PagesController.php 中加入:

<code>    public function contact() {
        return view('pages.contact');
    }</code>

新視圖 pages/contact.blade.php

<code>@extends('layout')

@section('content')
    <h1>Contact Me!</h1>
@stop</code>

Check it out!

在版面配置檔案中我們可以加入多個 @yield , 例如在 layout.blade.php 中加入 @yield('footer')

<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        @yield('content')
    </div>

    @yield('footer')
</body>
</html></code>

例如 contact.blade.php 中有一段腳本,就可以放在這個段中。

<code>@extends('layout')

@section('content')
    <h1>Contact Me!</h1>
@stop

@section('footer')
    <script>
        alert('Contact from scritp')
    </script>
@stop</code>

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

  • 使用 @if 來判斷
<code>@extends('layout')

@section('content')
    @if ($first = 'Zhang')
        <h1>Hello, Zhang</h1>
    @else
        <h1>Hello, nobody</h1>
    @endif
@stop</code>

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

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

@section('content')
    <h1>Person:</h1>
    <ul>
        @foreach($people as $person)
            <li>{{ $person }}</li>
        @endforeach
    </ul>
@stop</code>

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

<code>$people = [];</code>

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

<code>@extends('layout')

@section('content')
    @if (count($people))
        <h1>Person:</h1>
        <ul>
            @foreach($people as $person)
                <li>{{ $person }}</li>
            @endforeach
        </ul>
    @endif

    <h2>Other info</h2>
@stop</code>

That's better.

以上就介紹了Laravel 5 基礎(四)- Blade 簡介,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn