## Blade模板
在構建視圖時,不僅限于基本的PHP。你可以使用 `Laravel` 提供的強大模板引擎。我們將在以后更多地討論和使用 Blade 模板引擎。現在,讓我們利用它來創建一個布局文件,以減少頁面的重復性和復雜性。
### Blade 簡介
`Blade `是 `Laravel` 提供的一個簡單而又強大的模板引擎。和其他流行的 PHP 模板引擎不同,`Blade` 并不限制你在視圖中使用原生 `PHP` 代碼。所有 `Blade` 視圖文件都將被編譯成原生的 `PHP` 代碼并緩存起來,除非它被修改,否則不會重新編譯,這就意味著 `Blade` 基本上不會給你的應用增加任何負擔。`Blade` 視圖文件使用 `.blade.php` 作為文件擴展名,被存放在 `resources/views` 目錄。
`Blade` 的兩個主要優點是 `模板繼承` 和` 區塊` 。為方便入門,讓我們先通過一個簡單的例子來上手。
### 定義布局
在上一節基本路由中我們創建了 `about.blade.php` 視圖和 `news.blade.php` 視圖,這兩個視圖和基本基本的 `welcome.blade.php` 視圖 90% 代碼重復,下面我們創建一個布局。
```
<!-- 保存在 resources/views/layout.blade.php 文件中 -->
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title', 'Laravel')</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 13px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
</style>
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
@yield('content')
</div>
<div class="links">
<a href="/">Home</a>
<a href="/about">about</a>
<a href="/news">News</a>
</div>
</div>
</div>
</body>
</html>
```
### 繼承布局和區塊
* welcome.blade.php
```php
@extends('layout')
@section('title', 'Laravel')
@section('content')
Hello Laravel
@endsection
```
* about.blade.php
```php
@extends('layout')
@section('title', '關于我')
@section('content')
假裝寫代碼的晚黎
@endsection
```
* news.blade.php
```php
@extends('layout')
@section('title', 'Laravel News')
@section('content')
Laravel News
@endsection
```
### 總結
本節簡單的介紹了 `Blade` 模板引擎的兩大基本特性: `繼承` 、`區塊`。 `@yield` 指令在沒有數據的情況下第二個參數可以指定默認值:`@yield('title', 'Laravel News')` ,同時這個指令在生成 HTML代碼的時候不會產生換行。