Detailed Explanation of Blade Template Engine Example in Laravel

  • 2021-08-10 07:03:38
  • OfStack

Preface

This article mainly introduces the related contents of Blade template engine in Laravel, and shares it for your reference and study. Not much to say, let's take a look at the detailed introduction.

Blade template engine

Blade is a simple and powerful template engine provided by laravel, which compiles Blade views into native PHP code and caches them. The cache changes as the Blade view changes, which means that Blade does not impose a compile burden on your application. The Blade view files use the. blade. php suffix and are generally stored in the resources/views directory.

Template inheritance

Let's take 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
 
 <div class="container">
  @yield('content')
 </div>
 </body>
</html>

The Blade template file contains typical HTML tags. You must have seen the @ section and @ yield directives. The @ section directive defines a content block as its name implies, while the @ yield directive is used to display the content contained in the provided pendant block. We have defined a basic layout, and then we can use the @ extends directive of Blade to explicitly specify inheriting this layout. Then use the @ section directive to mount the contents of the pendant into the layout. In the above example, the contents of the pendant will be mounted into 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 pendant uses the @ parent directive to append the contents of the sidebar part of the layout, which will be overwritten if not used. The @ parent directive replaces the contents of the layout when the view is rendered.

The Blade view can use the global helper function view to return the rendered content just like the native PHP view 1:


Route::get('blade', function () {
 return view('child');
});

Display data

You can use curly braces {to display 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 as follows:


Hello, {{ $name }}

Of course, you can also return content from the native PHP method. In fact, you can use any PHP code in the Blade echo declaration: (Blade {{}} The contents of the declaration are automatically filtered by the htmlentities method to prevent XSS attacks. )


The current UNIX timestamp is {{ time() }}

Because many JavaScript frameworks use curly braces to indicate that the supplied 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 intact:


Hello, @{{ name }}

We often use 3-item operators to assign values


{{ isset($name) ? $name : 'Default' }}

Blade provides a convenient way to replace this 3 yuan declaration:


{{ $name or 'Default' }}

The default Blade {{}} declaration automatically uses the 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 to be attacked:


Hello, {!! $name !!}

Control structure

You can use the if control structure with the @ if, @ elseif, @ else, and @ endif directives:


<!-- 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
0

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


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

You can also use the @ hasSection directive to determine whether the pendant provided to the layout contains content:


<title>
 @hasSection('title')
 @yield('title') - App Name
 @else
 App Name
 @endif
</title>

When it comes to control, loop structure is indispensable, similar to PHP:


<!-- 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
3

Blade also provides instructions to terminate the iteration or cancel the current iteration:


<!-- 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
4

You can also use instruction declarations to include conditions to achieve interrupts:


<!-- 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
5

Include child views

You can use the @ include directive to include the contents of 1 view, and the variables in the current view are shared with child views:


<!-- 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
6

Although the child view automatically inherits all the data variables from the parent view, you can also directly pass an array variable to add additional variables to the child view (avoid __DIR__ and __FILE__ constants in the Blade view because they resolve to where the view is cached):


@include('view.name', ['some' => 'data'])

You can use the @ each directive of Blade to merge and introduce multiple views in one line:


@each('view.name', $jobs, 'job')

The first parameter is the name of the view that each element in the array or collection needs to be rendered.

The second parameter is an array or collection, which is used to provide iteration.

The third parameter is the variable name to be assigned to the current view.

You can also pass the fourth parameter to the @ each instruction. If the supplied array is empty, the view provided by this parameter will be introduced.


<!-- 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
9

Comments in Blade, so that writing will not be rendered:


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

Blade allows you to press content into a named heap:


@push('scripts')
 <script src="/example.js"></script>
@endpush

You can press the same heap as many times as you want, and you need to use @ stack in the layout to render the heap:


<head>
 <!-- Head Contents -->
 @stack('scripts')
</head>

You can use the @ inject directive to retrieve the service from the service container:


@inject('metrics', 'App\Services\MetricsService')
<div>
 Monthly Revenue: {{ $metrice->monthlyRevenue() }}
</div>

The first parameter will be the variable name of the retrieved service,

The second parameter is the name of the class or interface you want to retrieve in the service container.

You can use the directvie method to register instructions. When the Blade compiler encounters this instruction, it automatically calls the callback function provided when the instruction was registered and passes its parameters.

The following example creates the @ datetime ($val) directive to format $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() {
  //
 }
}

The above example uses the with helper method of Laravel, which simply returns a supplied object or value and provides a convenient chain call. Finally, the PHP code generated by this instruction is as follows:


 <?php echo with($var)->format('m/d/Y H:i'); ?>

After you update the logic of the Blade command, you should delete all cached Blade views, which you can use the view: clear Artisan command to clear.

Summarize


Related articles: