Detailed explanation of the Blade template engine example in Laravel, laravelblade

Source: Internet
Author: User

Detailed explanation of the Blade template engine example in Laravel, laravelblade

Preface

This article describes the Blade template engine in Laravel for your reference. Let's take a look at the details.

Blade template engine

Blade is a simple and powerful template engine provided by laravel. It compiles the Blade view into native PHP code and caches it. The cache changes when the Blade view changes. This means that Blade does not add compilation burden to your application. The Blade View File is suffixed with. blade. php and is generally stored in the resources/views directory.

Template inheritance

Let's look at an example.

<!-- Stored in resources/views/layouts/master.blade.php-->

The Blade template file contains a typical HTML Tag. You must have seen the @ section and @ yield commands. The @ section command defines a content block as its name implies, and the @ yield command is used to display the content contained in the provided pendant block. We have already defined a basic layout. Next we can use the @ extends command of Blade to explicitly specify to inherit this layout. Then use the @ section command to mount the content in the pendant to the layout. In the above example, the content of the pendant will be mounted to the @ yield section in 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 preceding example, the sidebar pendant uses the @ parent command to append the content of the sidebar part in the layout. If it is not used, this part of the layout will be overwritten. The @ parent command replaces the content in the layout when the view is rendered.

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

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

Show data

You can use curly braces {to display the variables passed to the view in the view. For example, you have defined the following routes:

Route::get('greeting', function () { return view('welcome', ['name' => 'Duicode']);})

You can output 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: (the content in the Blade {} Declaration is automatically filtered by the htmlentities method to prevent XSS attacks .)

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

Many JavaScript frameworks use curly brackets to indicate that the provided expressions should be displayed in the browser. Therefore, you can use the @ symbol to tell the Blade rendering engine that the expression is reserved as is:

Hello, @{{ name }}

We usually use the three-object operator to assign values.

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

Blade provides a convenient way to replace this three-element statement:

{{ $name or 'Default' }}

By default, the Blade {} Declaration automatically uses the htmlentities method to avoid XSS attacks. If you do not want your data to be escaped, you can use the following syntax, but be careful when attacked:

Hello, {!! $name !!}

Control Structure

You can use the if control structure through the @ if, @ elseif, @ else, And @ endif commands:

@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:

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

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

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

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

@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 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 command to declare conditions to interrupt:

@foreach ($users as $user) @continue($user->type == 1)  <li>{{ $user->name }}</li>  @break($user->number == 5)@endforeach

Contains sub-Views

You can use the @ include command to include the content of a view. The variables in the current view will also be shared to the subview:

<div> @include('shared.errors')  <form> <!-- Form Contents --> </form></div>

Although the child view automatically inherits all data variables in the parent view, you can also directly pass an array variable to add additional variables to the sub-view (avoid using _ DIR _ and _ FILE _ constants in the Blade view, because they will be resolved to the View cache location ):

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

You can use the @ each command of Blade to merge multiple views in one row:

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

The first parameter is the name of the view to be rendered for each element in an array or set.

The second parameter is an array or set used to provide iteration.

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

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

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

Note in Blade, so that the write will not be rendered:

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

Blade allows you to add content to the named heap:

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

You can press the same heap as needed. You need to use @ stack in the layout to render the heap:

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

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

The first parameter is used as 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 commands. When the Blade compiler encounters this instruction, it will automatically call the callback function provided during the instruction registration and pass its parameters.

In the following example, the @ datetime ($ val) command is created to format $ val:

<?phpnamespace 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 with help method of Laravel is used in the above example. It simply returns a provided object or value and provides convenient chained calls. The PHP code generated by this command 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. You can use the view: clear Artisan command to clear them.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.