Blade Template
Blade Template
- Introduction
- Template inheritance
- Components & Slots
- Display data
- Flow control
- Form
- Introducing subviews
- Stack
- Service Injection
- Blade Extension
Introduction
Blade is a simple yet powerful template engine provided by Laravel. Unlike other popular PHP template engines, Blade does not restrict you from using native PHP code in your views. All Blade view files will be compiled into native PHP code and cached, and will not be recompiled unless it is modified, which means that Blade will basically not add any burden to your application. Blade view files use .blade.php
as the file extension and are stored in the resources/views
directory.
Template inheritance
Define layout
The two main advantages of Blade are template inheritance
and blocks
. To get started, let's start with a simple example. First, let's look at a "main" page layout. Since most web applications use the same layout across different pages, it's easy to define a single Blade layout view:
<!-- 保存在 resources/views/layouts/app.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>
As you can see, this file contains typical HTML syntax. However, please note the @section
and @yield
directives. The @section
directive defines a part of the view, and the @yield
directive is used to display the content of the specified part.
Now that we have defined the layout of this application, we define a subpage that inherits this layout.
##Extended layoutWhen defining a subview, use Blade's@extends Directive specifies the view that the subview should "inherit" from. Views that extend Blade layout can inject content into layout sections using the
@section directive. As shown in the previous example, the content of these fragments will be displayed in the layout controlled by the
@yield directive:
<!-- 保存在 resources/views/child.blade.php 中 --> @extends('layouts.app') @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> @endsectionIn this example,
sidebar Fragments use the
@parent directive to append (rather than overwrite) content to the layout's sidebar. When the view is rendered, the
@parent directives will be replaced by the content in the layout.
{tip} Contrary to the previous example, here theBlade view can use the globalsidebar
fragment ends with
@endsectioninstead of
@show. The
@endsectiondirective only defines one section, while
@showyields this section immediately while defining it.
view assistant to return from routing:
Route::get('blade', function () { return view('child'); });Components & SlotsComponents and slots provide similar benefits to fragments and layouts; however, the mental model of components and slots is easier to understand. Let's first look at a reusable "alert" component that we want to reuse in our application:
<!-- /resources/views/alert.blade.php --> <div class="alert alert-danger"> {{ $slot }} </div>
{{ $slot }} The variable will contain the value we want to inject into The content of the component. Now, we build this component using Blade's
@component directive:
@component('alert') <strong>Whoops!</strong> Something went wrong! @endcomponentSometimes it is useful to define multiple slots for a component. Modify the alert component to allow it to inject "title". Named slots can be displayed via their matching "echo" variable:
<!-- /resources/views/alert.blade.php --> <div class="alert alert-danger"> <div class="alert-title">{{ $title }}</div> {{ $slot }} </div>We can now inject content into named slots using the
@slot directive. Content not within the
@slot directive will be passed to the
$slot variable in the component:
@component('alert') @slot('title') Forbidden @endslot You are not allowed to access this resource!@endcomponent
Passing additional data to the component
Sometimes you may need to pass additional data to the component. In this case, the containing data can be organized into an array as the second parameter of the @component
directive. All data will be provided to the component template as changes:
@component('alert', ['foo' => 'bar']) ... @endcomponent
Alias the components
If the components are stored in a subdirectory, you may wish to give them an alias for easy access. For example, if a Blade component is stored in resources/views/components/alert.blade.php
, you can use the component
method to components.alert## The alias for # is named
alert. . Normally, this process would be done in the
boot method of
AppServiceProvider:
use Illuminate\Support\Facades\Blade; Blade::component('components.alert', 'alert');Once the component has an alias, it can be rendered using a single directive:
@alert(['type' => 'danger']) You are not allowed to access this resource!@endalertIf there are no additional slots, you can also omit the component parameter:
@alert You are not allowed to access this resource!@endalert
The data passed to the Blade view can be displayed through variables wrapped in double curly braces. For example, given the following route:
Route::get('greeting', function () { return view('welcome', ['name' => 'Samantha']); });
, you can use the
name variable to display its content: Hello, {{ $name }}.
{{ }}Statements are automatically passed through PHP's
Not limited to displaying the contents of variables passed to the view, you can also display the results of any PHP function. In fact, you can put any PHP code you want in Blade's echo statement:htmlspecialchars
function to prevent XSS attacks.
The current UNIX timestamp is {{ time() }}.
By default, Blade The
{{ }} statement is automatically passed through PHP's htmlspecialchars
function to prevent XSS attacks. If you do not want the data to be escaped, you can use the following syntax: Hello, {!! $name !!}.
Sometimes, in order to initialize a JavaScript variable, you may pass a data to the view and render it into JSON:
<script> var app = <?php echo json_encode($array); ?>; </script>
However, you can use the
@json Blade directive instead of manually calling the json_encode
function: <script>
var app = @json($array);
</script>
By default, Blade (and Laravel's
e helpers) will double-encode HTML entities. If you want to disable double encoding, you can call the Blade::withoutDoubleEncoding
method in boot
of AppServiceProvider
: <?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider{
/**
* 引导任意应用服务。
*
* @return void
*/
public function boot()
{
Blade::withoutDoubleEncoding();
}
}
Blade & JavaScript Framework
Since many JavaScript frameworks also use curly braces to indicate that a given expression will be displayed in the browser, you can use the @
symbol to notify the Blade rendering engine of a certain The expression should remain unchanged. An example is as follows:
<h1>Laravel</h1>Hello, @{{ name }}.
In this example, the @
symbol will be deleted by Blade; in the Blade engine, the {{ name }}
expression will remain unchanged, Instead, the JavaScript engine will render the expression.
@verbatim
Commands
If you want to use JavaScript variables in a large template, you can wrap the HTML in @verbatim
directive, so there is no need to add the @
symbol to each Blade echo statement:
@verbatim <div class="container"> Hello, {{ name }}. </div>@endverbatim
Control Structure
In addition to template inheritance and data display, Blade also provides convenient shortcuts for PHP control structures such as branching and looping. These shortcuts provide a clean, simple way to work with PHP control structures while maintaining similarity to their counterparts in PHP.
##If statement can use@if,
@elseif## The #, @else
, and @endif
directives construct if
statements. These directives function identically to the corresponding PHP directives:
For convenience, Blade also provides the @if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif
directive:
In addition to the conditional directives already discussed, The @unless (Auth::check())
You are not signed in.@endunless
and @empty
directives can be used as shortcuts to their corresponding PHP functions: @isset($records)
// $records 被定义且不是 null...
@endisset
@empty($records)
// $records 为空...
@endempty
#@auth
and@guest directives can be used to quickly determine whether the current user is authenticated or a guest:
@auth // 此用户身份已验证...@endauth @guest // 此用户身份未验证...@endguest
can be used if needed
@auth and @guest directives specify the identity that should be verified:
@auth('admin') // 此用户身份已验证...@endauth @guest('admin') // 此用户身份未验证...@endguest
Fragment directivescan be used@hasSection
The command checks whether the section has content:@hasSection('navigation') <div class="pull-right"> @yield('navigation') </div> <div class="clearfix"> </div> @endif
,
@case, @break
, @default
and @endswitch
instructions construct switch statements: @switch($i)
@case(1)
First case...
@break
@case(2)
Second case...
@break
@default
Default case...@endswitch
In addition to branch statements, Blade also provides simplified instructions that are the same as PHP's loop structure. The functions of these instructions are also the same as the corresponding PHP instructions: {tip} You can use loop variables in the loop to obtain the evaluable information of the loop, such as it is currently in the loop In the first iteration or the last iteration: In a loop, you can also terminate the loop or pass through this iteration: You can also declare a conditional in one line Instruction: During the loop, there is an available In nested loops, you can use Loops
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
@while (true)
<p>I'm looping forever.</p>
@endwhile
@foreach ($users as $user)
@if ($user->type == 1)
@continue
@endif
<li>{{ $user->name }}</li>
@if ($user->number == 5)
@break
@endif@endforeach
@foreach ($users as $user)
@continue($user->type == 1)
<li>{{ $user->name }}</li>
@break($user->number == 5)
@endforeach
Loop variable
$ in the loop body loop
variable. This variable provides access to a small amount of useful information such as the index of the current loop and whether it is the first or last loop: @foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
parent
Properties access the parent loop's $loop
variable: @foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is first iteration of the parent loop.
@endif
@endforeach@endforeach
$loop
The variable also contains several other useful properties:
Properties | Description |
---|---|
##$loop->index
| The index of the current iteration (counting from 0). |
$loop->iteration
| Current loop iteration (counted from 1). |
$loop->remaining
| The number of remaining iterations in the loop. |
$loop->count
| The total number of array elements being iterated. |
$loop->first
| is the first iteration of the loop. |
$loop->last
| is the last iteration of the loop. |
$loop->depth
| The nesting depth level of the current iteration. |
$loop->parent
| In nested loops, the loop variable of the parent loop