[Laravel5.2 documentation] basics-Blade template engine 1. Introduction
Blade is a simple but powerful template engine provided by Laravel. Unlike other popular PHP template engines, Blade does not constrain you to use PHP native code in the view. All Blade views are compiled into native PHP code and cached until modified. This means that Blade basically has no overhead for application performance. The Blade view file is extended using the. blade. php file and stored in the resources/views directory.
2. template inheritance definition layout
The two biggest advantages of using Blade are template inheritance and slicing. let's take a look at an example before getting started. First, we detect a "main" page layout. because most Web applications use the same layout in different pages, we can easily define this layout as a separate Blade page:
App Name-@ yield ('title ') @ Section ('inclubar') This is the master sidebar. @ show@ Yield ('content ')
As you can see, this file contains a typical HTML tag. However, note that the @ section and @ yield commands define a content segment as its name implies, the latter is used to display the content of a given segment.
Now we have defined a layout for the application. let's define the child pages that inherit the layout.
Extended layout
When defining a child page, you can use the @ extends command of Blade to indicate the layout inherited by the child page, the view that inherits a Blade layout uses the @ section command to inject content into the layout fragment. Remember, as shown in the preceding example, the content of these fragments will be displayed in the layout where @ yield is used:
@ Extends ('layouts. master') @ section ('title', 'Page title') @ section ('inclubar') @ parentThis is appended to the master sidebar.
@ Endsection @ section ('content ')This is my body content.
@ Endsection
In this example, the sidebar fragment uses the @ parent command to append (rather than overwrite) the content to the layout sidebar. the @ parent command will be replaced by the layout content during view rendering.
Of course, the Blade view can be directly returned from the route using the view method as the native PHP view sample:
Route::get('blade', function () { return view('child');});
3. Data Display
You can wrap variables in two curly brackets to display the data transmitted to the view. for example, if the following route is provided:
Route::get('greeting', function () { return view('welcome', ['name' => 'Samantha']);});
You can display the content of the name variable as follows:
Hello, {{ $name }}.
Of course, you can output any PHP function without limiting the variable content displayed in the view. In fact, you can put any PHP code into the Blade template statement:
The current UNIX timestamp is {{ time() }}.
Note: The Blade {} statement has been processed by the htmlentities function of PHP to avoid XSS attacks.
Blade & JavaScript framework
Many JavaScript frameworks use curly brackets to indicate expressions to be displayed in the browser. you can use the @ symbol to tell the Blade rendering engine that the expression should remain in the native format. For example:
LaravelHello, @{{ name }}.
In this example, the @ operator will be removed by Blade. However, the {name} expression will remain unchanged to avoid rendering by the JavaScript framework.
Output existing data
Sometimes you want to output a variable, but you are not sure whether the variable is set. we can use the following PHP code:
{{ isset($name) ? $name : 'Default' }}
In addition to the ternary operator, Blade provides a simpler method:
{{ $name or 'Default' }}
In this example, if the $ name variable exists, its value is displayed; otherwise, "Default" is displayed ".
Display native data
By default, the Blade {} statement has been processed through the htmlentities function of PHP to avoid XSS attacks. if you do not want data to be processed, you can use the following syntax:
Hello, {!! $name !!}.
Note: Be careful when outputting the content provided by the user. always use double curly braces for the content provided by the user to avoid directly outputting HTML code.
4. Process control
In addition to template inheritance and data display, Blade also provides convenient operations for common PHP process control, such as conditional statements and loops, these shortcut operations provide a clean and simple way to handle PHP process control, while keeping them similar to the corresponding PHP statements.
If statement
You can use @ if, @ elseif, @ else and @ endif to construct the if statement. These command functions are the same as those in PHP:
@if (count($records) === 1) I have one record!@elseif (count($records) > 1) I have multiple records!@else I don't have any records!@endif
For convenience, Blade also provides the @ unless command:
@unless (Auth::check()) You are not signed in.@endunless
Loop
In addition to the conditional statements, Blade also provides simple instructions to process the loop structures supported by PHP. Similarly, these directive functions are the same as those supported by PHP:
@for ($i = 0; $i < 10; $i++) The current value is {{ $i }}@endfor@foreach ($users as $user) This is user {{ $user->id }}
@endforeach@forelse ($users as $user)
{{ $user->name }} @empty
No users
@endforelse@while (true)
I'm looping forever.
@endwhileContains sub-views
The @ include command of Blade allows you to easily include another Blade view in one view. all the variables in the parent view are still valid in the included child view:
@include('shared.errors')
Although the contained view inherits data from all parent views, you can pass additional parameters to the included view:
@include('view.name', ['some' => 'data'])
Note: Do not use the _ DIR _ and _ FILE _ constants in the Blade view because they point to the cache view path.
Rendering a view for a set
You can use the @ each command of Blade to introduce multiple local views through a code loop:
@each('view.name', $jobs, 'job')
The first parameter of this command is the partial view to be rendered by each element in an array or set. The second parameter is the array or set you want to iterate over, the third parameter is the variable name to be allocated to the current view. For example, if you want to iterate a jobs array, you usually need to access the $ job variable in the local view.
You can also pass the fourth parameter to the @ each command, which is used to specify the View rendered when the given array is empty:
@each('view.name', $jobs, 'job', 'view.empty')
Note
Blade also allows you to define comments in the view. However, unlike HTML comments, Blade comments are not included in HTML and are returned:
{{-- This comment will not be present in the rendered HTML --}}
5. service injection
The @ inject command can be used to obtain the service from the service container. The first parameter passed to @ inject is the variable name of the service to be placed, the second parameter is the service class name or interface name to be parsed:
@inject('metrics', 'App\Services\MetricsService') Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
6. extend the Blade
Blade even allows you to customize commands. you can use the directive method to register an instruction. When the Blade compiler encounters this instruction, it will pass in the parameter and call the provided callback.
The following example creates a @ datetime ($ var) command to format the given $ var:
Format ('m/d/y h: I ');?> ";}) ;}/ *** Register and bind in the container. ** @ return void */public function register (){//}}
As you can see, Laravel's helper function with is used in this command. the with method simply returns the given object/value, allowing the method chain. The PHP code generated by this command is as follows:
format('m/d/Y H:i'); ?>