昨天我們學會了用 Controller 把資料和功能分開,今天要學的是 Blade 模板引擎,它可以讓我們更方便的把資料和 HTML 結合,做出漂亮且容易維護的網頁!!
Blade 是 Laravel 內建的「網頁模板工具」,就像是「網頁的拼裝工廠」:
好處是:
所有 Blade 模板放在:resources/views/
副檔名是 .blade.php
例如 welcome.blade.php
假設 Controller 傳了一個變數 $name
:
public function hello()
{
$name = "Amy";
return view('welcome', ['name' => $name]);
}
在 resources/views/welcome.blade.php
:
<h1>你好,{{ $name }}!</h1>
瀏覽器顯示:
你好,Amy!
{{ $變數 }}
就是 Blade 顯示資料的方式。
@if($age >= 18)
<p>你已滿 18 歲</p>
@else
<p>未滿 18 歲</p>
@endif
<ul>
@foreach($items as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
<html>
<body>
<header>我的網站</header>
<main>
@yield('content')
</main>
</body>
</html>
子頁面繼承它:
@extends('layout')
@section('content')
<h1>首頁內容</h1>
@endsection
這樣可以避免每個頁面重複寫 header、footer
{{ }}
顯示資料、@if 條件判斷、@foreach 迴圈