Featured image of post Day 7. View 的模板引擎: Blade

Day 7. View 的模板引擎: Blade

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

專案連結: github - laravel7 之 30 天分享

上一篇: Day 6. 第一個頁面: Controller & View
今天來跟大家分享模板引擎 Blade 的使用方式

使用

可以先參考 官方文檔
基本語法都是使用 @

舉個例子,
我們平常使用的 if

1
2
3
4
5
6
7
8
9
<?php 
if (true) {
    echo 1;
} elseif (true) {
    echo 2;
} else {
    echo 3;
}
?>

使用blade的話,則是這樣用的

1
2
3
4
5
6
7
@if (true)
    1
@elseif (true)
    2
@else
    3
@endif

繼承使用 (extends、yield、section)

可以建立一個主要的 Blade,把 header、footer 放進去
其他直接使用 @extend ,如以下範例

  • 主要檔案 resources/views/day7/layouts/app.blade.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

動態內容可以使用 @yield@section 搭配

  • 內容檔案 resources/views/day7/testContent.blade.php
1
2
3
4
5
6
7
@extends('day7.layouts.app')

@section('title', '測試標題')
 
@section('content')
    <p>測試內文.</p>
@endsection

直接引入 indclude

有些像是 header、footer 就可以使用 @indclude 的方式直接引入檔案

以剛剛的 layouts/app 為例

  • 檔案 resources/views/day7/layouts/app.blade.php
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @include('day7.layouts.header')
 
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

就可以在 resources/views/day7/layouts/header.blade.php 編寫 header 的內容, 這樣看起來就會更加乾淨一些。

foreach

另外提一個,我們平常頁面很長會使用 foreach Laravel 在這一段還提供了 Loop 參數可以使用
可以參考 loop 參數文件

PropertyDescription
$loop->indexThe index of the current loop iteration (starts at 0).
$loop->iterationThe current loop iteration (starts at 1).
$loop->remainingThe iterations remaining in the loop.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration through the loop.
$loop->lastWhether this is the last iteration through the loop.
$loop->evenWhether this is an even iteration through the loop.
$loop->oddWhether this is an odd iteration through the loop.
$loop->depthThe nesting level of the current loop.
$loop->parentWhen in a nested loop, the parent’s loop variable.

others

  1. method 之前 Day 5. 路由: Router 有提到 route method 我們就需要在表單設定 @method
1
2
3
<form>
    @method('PUT')
</form>
  1. 登入/訪客 有沒有登入也可以在 Blade 設定
1
2
3
4
5
6
7
@auth
    // 有登入
@endauth
 
@guest
    // 訪客(未登入)
@endguest

DEMO

此時瀏覽 /bladeTest 就會看到頁面了!

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy