Home > Article > Backend Development > Detailed explanation of Blade template engine in Laravel
Laravel's template engine uses the blade template engine. The following article mainly introduces you to the relevant information about the Blade template engine in Laravel. The article introduces it in great detail through sample code, which is of certain significance for everyone's study or work. Referring to the value of learning, friends in need can follow the editor to learn together.
Preface
This article mainly introduces to you the relevant content about the Blade template engine in Laravel, and shares it for your reference and study. Enough said, let’s take a look at the detailed introduction.
Blade template engine
Blade is a simple and powerful template engine provided by laravel. It compiles Blade views into native PHP code and cache it. The cache changes when the Blade view changes, which means Blade adds no compilation burden to your application. Blade view files use the .blade.php suffix and are generally stored in the resources/views directory.
Template inheritance
Let’s look at an example first
<!-- 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 <p class="container"> @yield('content') </p> </body> </html>
Blade template files contain typical HTML markup. You must have seen the @section and @yield directives. The @section directive defines a content section as its name suggests, while the @yield directive is used to display the content contained in the provided widget section. Now that we have defined a basic layout, we can use Blade's @extends directive to explicitly inherit this layout. Then use the @section directive to mount the content of the widget into the layout. In the above example, the content of the widget will be mounted to the @yield section of the layout:
<!-- 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
In the above example, the sidebar widget uses the @parent directive to append the content of the sidebar part of the layout. If not used, this part of the layout will be overwritten. The @parent directive replaces the content of the layout with the content when the view is rendered.
Blade views can use the global helper function view to return rendered content just like native PHP views:
Route::get('blade', function () { return view('child'); });
Display data
You can use curly braces { to display the variables passed to the view in the view. For example, you define the following route:
Route::get('greeting', function () { return view('welcome', ['name' => 'Duicode']); })
You can output the contents of the name variable in the view like this:
Hello, {{ $name }}
Of course, you can also use the native PHP method Return content. In fact, you can use arbitrary PHP code in the Blade echo declaration: (The content in the Blade {{}} declaration is automatically filtered through the htmlentities method to prevent XSS attacks.)
The current UNIX timestamp is {{ time() }}
Because many JavaScript frameworks use curly braces to indicate that the provided expression should be displayed in the browser. So you can use the @ symbol to tell the Blade rendering engine that you want the expression to remain as is:
Hello, @{{ name }}
We often use the ternary operator to assign values
{{ isset($name) ? $name : 'Default' }}
Blade provides a convenient way to replace this ternary declaration:
{{ $name or 'Default' }}
The default Blade {{}} declaration will be automatically used htmlentities method to avoid XSS attacks. If you don't want your data to be escaped, you can use the following syntax, but be careful and be careful of being attacked:
Hello, {!! $name !!}
Control structure
You can use the if control structure through the @if, @elseif, @else and @endif directives:
@if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif
Of course, for convenience, Blade also provides an alternative command @unless command:
@unless (Auth::check()) You are not signed in. @endunless
You can also use the @hasSection command to determine the widgets provided to the layout Whether the content is included:
<title> @hasSection('title') @yield('title') - App Name @else App Name @endif </title>
Speaking of control, a loop structure is indispensable, similar to PHP:
@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
Blade also Provides instructions to terminate iteration or cancel the current iteration:
@foreach ($users as $user) @if($user->type == 1) @continue @endif <li>{{ $user->name }}</li> @if($user->number == 5) @break @endif @endforeach
You can also use the instruction statement to achieve interruption by including conditions:
@foreach ($users as $user) @continue($user->type == 1) <li>{{ $user->name }}</li> @break($user->number == 5) @endforeach
Include subviews
You can use the @include directive to include the contents of a view, and the variables in the current view will also Shared to child views:
<p> @include('shared.errors') <form> <!-- Form Contents --> </form> </p>
Although child views automatically inherit all data variables from the parent view, you can also pass an array variable directly to add additional variables to Subviews (avoid using the __DIR__ and __FILE__ constants in Blade views as they resolve to where the view cache is):
@include('view.name', ['some' => 'data'])
You can use Blade's @ The each directive combines and introduces multiple views in one line:
@each('view.name', $jobs, 'job')
The first parameter is the name of the view that needs to be rendered for each element in the array or collection.
The second parameter is an array or collection, which is used to provide iteration.
第三个参数是要分配给当前视图的变量名。
你也可以传递第四个参数到 @each 指令。如果所提供的数组是空数组的话,该参数所提供的视图将会被引入。
@each('view.name', $jobs, 'job', 'view.empty')
Blade 中的注释,这样写不会被渲染:
{{-- This comment will not be present in the rendered HTML --}}
Blade 允许你在已命名的堆中压入内容:
@push('scripts') <script src="/example.js"></script> @endpush
你可以在你需要的时候压入相同的堆任意的次数,你需要在布局中使用 @stack 来渲染堆:
<head> <!-- Head Contents --> @stack('scripts') </head>
可以使用 @inject 指令来从服务容器中取回服务:
@inject('metrics', 'App\Services\MetricsService') <p> Monthly Revenue: {{ $metrice->monthlyRevenue() }} </p>
第一个参数将作为所取回服务存放的变量名,
第二个参数是你想要在服务容器中取回的类或接口名称。
可以使用 directvie 方法来注册指令。当 Blade 编译器遇到该指令时,它会自动的调用该指令注册时提供的回调函数并传递它的参数。
下面的例子创建了 @datetime($val) 指令来格式化 $val:
<?php namespace App\Providers; use Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider{ /** * Perform post-registration booting of services. * * @return void */ public function boot(){ Blade::directive('datetime', function ($expression) { return "<?php echo with{$express}->format('m/d/Y H:i'); ?>"; }); } /** * Register bindings in the container * * @return void */ public function register() { // } }
上面的例子中使用了 Laravel 的 with 帮助方法,它只是简单的返回一个所提供的对象或值,并提供方便的链式调用。最终该指令生成的 PHP 代码如下:
<?php echo with($var)->format('m/d/Y H:i'); ?>
在你更新 Blade 指令的逻辑之后,你应该删除所有已缓存的 Blade 视图,你可以使用 view:clear Artisan 命令来清除。
总结
The above is the detailed content of Detailed explanation of Blade template engine in Laravel. For more information, please follow other related articles on the PHP Chinese website!