Home > Backend Development > PHP Tutorial > Detailed explanation of Blade template engine in Laravel

Detailed explanation of Blade template engine in Laravel

黄舟
Release: 2023-03-16 15:18:01
Original
3407 people have browsed it

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(&#39;title&#39;)</title>
 </head>
 <body>
 @section(&#39;sidebar&#39;)
  This is the master sidebar.
 @show
 
 <p class="container">
  @yield(&#39;content&#39;)
 </p>
 </body>
</html>
Copy after login

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(&#39;layouts.master&#39;)
 
@section(&#39;title&#39;, &#39;Page Title&#39;)
 
@section(&#39;sidebar&#39;)
 @parent
 
 <p>This is appended to the master sidebar.</p>
@endsection
 
@section(&#39;content&#39;)
 <p>This is my body content.</p>
@endsection
Copy after login

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(&#39;blade&#39;, function () {
 return view(&#39;child&#39;);
});
Copy after login

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(&#39;greeting&#39;, function () {
 return view(&#39;welcome&#39;, [&#39;name&#39; => &#39;Duicode&#39;]);
})
Copy after login

You can output the contents of the name variable in the view like this:


Hello, {{ $name }}
Copy after login

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() }}
Copy after login

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 }}
Copy after login

We often use the ternary operator to assign values


{{ isset($name) ? $name : &#39;Default&#39; }}
Copy after login

Blade provides a convenient way to replace this ternary declaration:


{{ $name or &#39;Default&#39; }}
Copy after login

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 !!}
Copy after login

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&#39;t have any records!
@endif
Copy after login

Of course, for convenience, Blade also provides an alternative command @unless command:


@unless (Auth::check())
 You are not signed in.
@endunless
Copy after login

You can also use the @hasSection command to determine the widgets provided to the layout Whether the content is included:


<title>
 @hasSection(&#39;title&#39;)
 @yield(&#39;title&#39;) - App Name
 @else
 App Name
 @endif
</title>
Copy after login

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&#39;m looping forever.</p>
@endwhile
Copy after login

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
Copy after login

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
Copy after login

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(&#39;shared.errors&#39;)
 
 <form>
 <!-- Form Contents -->
 </form>
</p>
Copy after login

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(&#39;view.name&#39;, [&#39;some&#39; => &#39;data&#39;])
Copy after login

You can use Blade's @ The each directive combines and introduces multiple views in one line:


@each(&#39;view.name&#39;, $jobs, &#39;job&#39;)
Copy after login

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(&#39;view.name&#39;, $jobs, &#39;job&#39;, &#39;view.empty&#39;)
Copy after login

Blade 中的注释,这样写不会被渲染:


{{-- This comment will not be present in the rendered HTML --}}
Copy after login

Blade 允许你在已命名的堆中压入内容:


@push(&#39;scripts&#39;)
 <script src="/example.js"></script>
@endpush
Copy after login

你可以在你需要的时候压入相同的堆任意的次数,你需要在布局中使用 @stack 来渲染堆:


<head>
 <!-- Head Contents -->
 @stack(&#39;scripts&#39;)
</head>
Copy after login

可以使用 @inject 指令来从服务容器中取回服务:


@inject(&#39;metrics&#39;, &#39;App\Services\MetricsService&#39;)
<p>
 Monthly Revenue: {{ $metrice->monthlyRevenue() }}
</p>
Copy after login

第一个参数将作为所取回服务存放的变量名,

第二个参数是你想要在服务容器中取回的类或接口名称。

可以使用 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(&#39;datetime&#39;, function ($expression) {
  return "<?php echo with{$express}->format(&#39;m/d/Y H:i&#39;); ?>";
  });
 }
 
 /**
 * Register bindings in the container
 *
 * @return void
 */
 public function register() {
  //
 }
}
Copy after login

上面的例子中使用了 Laravel 的 with 帮助方法,它只是简单的返回一个所提供的对象或值,并提供方便的链式调用。最终该指令生成的 PHP 代码如下:


<?php echo with($var)->format(&#39;m/d/Y H:i&#39;); ?>
Copy after login

在你更新 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template