前言
本文主要給大家介紹了關(guān)于Laravel中Blade模板引擎的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),話不多說了,來一起看看詳細(xì)的介紹吧。
Blade 模板引擎
Blade 是 laravel 提供的一個(gè)簡(jiǎn)單強(qiáng)大的模板引擎,它是把 Blade 視圖編譯成原生的 PHP 代碼并緩存起來。緩存會(huì)在 Blade 視圖改變時(shí)而改變,這意味著 Blade 并沒有給你的應(yīng)用添加編譯的負(fù)擔(dān)。Blade 視圖文件使用 .blade.php 后綴,一般都存儲(chǔ)在 resources/views 目錄下。
模板繼承
先來看個(gè)例子
<!-- Stored in resources/views/layouts/master.blade.php--> <html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @show <div class="container"> @yield('content') </div> </body> </html>
Blade 模板文件包含了典型的 HTML 標(biāo)記。你肯定看到了 @section 和 @yield 指令。@section 指令就如它的名字所暗示的那樣定義了一個(gè)內(nèi)容區(qū)塊,而 @yield 指令是用來顯示所提供的掛件區(qū)塊所包含的內(nèi)容。我們已經(jīng)定義好了一個(gè)基本的布局,接下來我們可以使用 Blade 的 @extends 指令來明確的指定繼承這個(gè)布局。然后使用 @section 指令將掛件中的內(nèi)容掛載到布局中,在上面的例子中,掛件的內(nèi)容將被掛載到布局中的 @yield 部分:
<!-- Stored in resoures/views/child.blade.php --> @extends('layouts.master') @section('title', 'Page Title') @section('sidebar') @parent <p>This is appended to the master sidebar.</p> @endsection @section('content') <p>This is my body content.</p> @endsection
在上面的例子作用 sidebar 掛件利用 @parent 指令來追加布局中的 sidebar 部分的內(nèi)容,如果不使用則會(huì)覆蓋掉布局中的這部分。@parent 指令會(huì)在視圖被渲染時(shí)替換為布局中的內(nèi)容。
Blade 視圖可以像原生 PHP 視圖一樣使用全局幫助函數(shù) view 來返回渲染后的內(nèi)容:
Route::get('blade', function () { return view('child'); });
顯示數(shù)據(jù)
你可以使用花括號(hào) { 來在視圖中顯示傳遞到視圖中的變量,例如,你定義了下面的路由:
Route::get('greeting', function () { return view('welcome', ['name' => 'Duicode']); })
你可以在視圖中這樣來輸出 name 變量的內(nèi)容:
Hello, {{ $name }}
當(dāng)然,你也可以從原生 PHP 方法中返回內(nèi)容。事實(shí)上,你可以在 Blade echo 聲明中使用任意的 PHP 代碼:(Blade {{}} 聲明中的內(nèi)容是自動(dòng)通過 htmlentities 方法過濾的,用來防止 XSS 攻擊。)
The current UNIX timestamp is {{ time() }}
由于很多 JavaScript 框架都使用花括號(hào)來表明所提供的表達(dá)式應(yīng)該被顯示在瀏覽器中。所以你可以使用 @ 符號(hào)來告訴 Blade 渲染引擎你需要這個(gè)表達(dá)式原樣保留:
Hello, @{{ name }}
我們常用三目運(yùn)算符來賦值
{{ isset($name) ? $name : 'Default' }}
Blade 提供了一個(gè)便捷的方式來替換這個(gè)三元聲明:
{{ $name or 'Default' }}
默認(rèn)Blade {{}} 聲明會(huì)自動(dòng)的使用 htmlentities 方法來避免 XSS 攻擊。如果你不想你的數(shù)據(jù)被轉(zhuǎn)義,你可以使用下面的語法,但是要注意,小心被攻擊:
Hello, {!! $name !!}
控制結(jié)構(gòu)
你可以通過 @if,@elseif,@else和 @endif 指令來使用 if 控制結(jié)構(gòu) :
@if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif
當(dāng)然為了方便,Blade 也提供了替代指令 @unless 指令:
@unless (Auth::check()) You are not signed in. @endunless
也可以使用 @hasSection 指令來判斷提供給布局的掛件是否包含了內(nèi)容:
<title> @hasSection('title') @yield('title') - App Name @else App Name @endif </title>