Laravel 5. Middleware and views and instances of the blade template engine

Source: Internet
Author: User
Tags closing tag compact php framework yii

First, the middleware

Laravel's HTTP middleware provides a layer of filtering and protection for routing. The following simulates the use of middleware authentication background login.

1. Creating middleware

CMD window into the project directory, using the artisan command to create


PHP Artisan Make:middleware adminloginverify

This will create the middleware in the App/http/middleware directory adminloginverify

Add the validation logic in the handle () method of the Adminloginverify class:


<?phpnamespace app\http\middleware;use closure;class adminloginverify{public    function handle ($request, Closure $next)    {if        (!session (' admin ')) {//If no login is directed to the login page            return redirect (' Admin/login ');        }        Return $next ($request);}    }

OK, now create and define the middleware that validates the login adminloginverify

2. Register Middleware

Find the protected $routeMiddleware attribute in the app/http/kernel.php file and append our adminloginverify


protected $routeMiddleware = [        ' auth ' = + \app\http\middleware\authenticate::class,        ' auth.basic ' and ' = ' Illuminate\auth\middleware\authenticatewithbasicauth::class,        ' can ' = \illuminate\foundation\http\ Middleware\authorize::class,        ' guest ' = \app\http\middleware\redirectifauthenticated::class,        ' Throttle ' = + \illuminate\routing\middleware\throttlerequests::class,         //Custom middleware        ' adminloginverify ' = \app\http\middleware\adminloginverify::class,    ];

3. Add a route

Add routes in the app/http/routes.php file:


Background home routing, exit login route route::group ([' prefix ' = ' admin ', ' namespace ' = ' admin ', ' middleware ' = ' adminloginverify ') , function () {    route::get (' index ', ' Indexcontroller@index ');    Route::get (' logout ', ' indexcontroller@logout '); /Background Login Route route::group ([' middleware ' = ' web '], function () {    route::get (' Admin/login ', ' admin\ Indexcontroller@login ');});

This is the code for the Index controller in the background admin directory:


<?phpnamespace app\http\controllers\admin;use App\http\controllers\controller;class IndexController extends controller{    //Backstage Home public    function index () {        return ' 

4. Analog Login

Open the browser, access the background login page

OK, visit the Backstage homepage

Now we're logged out.

In the exiting state, the Access homepage is redirected to the login page.

Second, the View

1. Rendering views, assigning data

Method 1: Array key-value pairs are assigned


In the Controller $data = Array (    ' title ' = = ' Laravel ', ' subTitle ' = ' + '    efficient PHP framework '); return view (' My_laravel ', $data) ;//<?php echo $title in the template;? ><?php echo $subTitle;? >

Method 2. With method chain Assignment


In the Controller return view (' My_laravel ')->with (' title ', ' Laravel ')->with (' subTitle ', ' efficient and fast PHP framework ');//In the template (as in the above) <?php echo $title;? ><?php echo $subTitle;? >

Method 3. Use compact () function assignment


In the Controller $data = Array (    ' title ' = ' Laravel ',    ' subTitle ' = ' + ' efficient PHP framework '); $content = ' Laravel 5.2 continues on 5.1 basis Improvements and optimizations, added many new features ... '; return view (' My_laravel ', compact (' data ', ' content '),//In the template (unlike the first two) <?php echo $data [' ><?php echo $data [' subTitle '];? ><?php echo $content;?>

Where the first parameter of the view () function is the name of the My_laravel, which in the Resources/views view directory, the template file suffix is. blade.php, using the blade template engine.

Three, Blade template engine

1. Output variables


Output a single variable {{$var}}//keep the double brace, compile to {{var}}@{{var}}//can output the default value {{$var or ' I am the default '}}{{isset ($var)? $var: ' I am the default '}}//Bla De comment {{--this comment is not output to the page--}}//ignore character manifested, output JS or html{!! $var!!} Note: Because the Blade template engine defaults to the htmlentities character of the {{}} statement, you should use the above syntax when you want to output JS or HTML code

2. Process Control


If statement @if ($var = = ' Laravel ')    I am laravel@elseif ($var = = ' Yii ')    I am yii@else    i don ' t know what I am. @endif/ /cyclic @for ($i = 0; $i < $i + +)    The current value is {$i}} @endfor @foreach ($array as $v)    <p> I am an array member {{ $v}}</p> @endforeach @forelse ($users as $v)    <li> My name is {{$v->name}}</li>    @empty    <p> I don't have a name </p> @endforelse @while (true)    <p> I've been looping ...</p> @endwhile//Can nest @for ($i = 0; $i < 10; $i + +)    @if ($i > 5)        I am {{$i}} > 5    @endif @endfor

3. Template layouts and sub-views

@include file contains directives.

@extends template inheritance directives.

@yield the SLICE Definition directive (define the slice display location).

@section Slice provides instructions (define slice details).

@endsection the closing tag for the @section.

@show the end tag of the @section, providing the slice content while displaying the slice.

@parent a @section content tag that displays a slice of the parent template.

@include: contains a child view, that is, the file contains.

If multiple pages in a site have public sections, such as top navigation, sidebar recommendations, and bottom copyright. To facilitate later maintenance and modification, the public sections of these pages can be taken out as separate files, placed in the common folder under the View directory, and named Top.balde.php, aside.blade.php, and bottom.blade.php, respectively. So in our various view templates, you can use the

@include (' common.top ')//The top navigation is included, and the other public parts are handled equally.

If you need to pass a variable, you can add a parameter

@include (' Common.top ', [' location ' = ' home '])

@extends: template inheritance, which inherits the layout of the parent template.

In @include directive, it is included in the part of the template that is picked out.

The @extends directive inherits an existing layout of the master template.

Now there is a layouts directory under the View directory, and the directory has a main template master.blade.php, the layout is as follows:


<! DOCTYPE html>

@yield (' title ', ' home ') directive defines the page title to be displayed in the <title> tab

@yield (' main ') defines the main content that is displayed between the top and the sidebar.

So where is the title and the main content? This requires a sub-template.

Now we create a new sub-template child.blade.php in the view directory, which reads as follows:


@extends (' Layouts.master ') @section (' title ')    about page @endsection@section (' main ')    <p class= "main" > "About Page" Main content </p> @endsection

  

Define a route that points to the Master Master template View and child template view, accessing the child view in the browser

We see that the child template inherits the contents of the Master Master template: Top, sidebar, bottom

At the same time, the child template also displays its own page title "About page" and main content "About page" main content "

This is the credit of the slicing provider @section @endsection in the Master Master template @yield and the child template.

@yield, @section: Define slices and provide slices.

The @yield (' main ') directive defines an HTML slice, which indicates that a slice named ' main ' is displayed at this location

The @section (' main ') @endsection instruction provides an HTML slice that provides detailed content for the ' Mian ' slice defined by @yield (' main ').

Then with the slice display location, with the details of the slice, you can display a detailed HTML slice.

It should be noted that in master template master there is such a


@yield (' title ', ' Home ')

It indicates the default value for the ' title ' Slice. That is, if no child template inherits the main template, or inherits but does not provide the ' title ' Slice with the @section (' title ') @endsection instruction, it will display a default value of ' home '.

Now, direct access to the main template to see

Yes, there is no sub-template with @section (' title ') @endsection to provide the title, @yield (' title ', ' Home page ') shows the ' title ' Slice default value ' home '.

So, the main template as the homepage of the site, its main content? If it is to be displayed, do you want to write a sub-template to inherit it, and then use the @section @endsection to provide the main content? Can not directly in the main template to write a similar @yield (' title ', ' Home ') to provide the default value?

Of course you can, rewrite the main template below.


<! DOCTYPE html>

@section (' main ') @show can provide a ' main ' slice and display it.

Now visit the main template to see, home main content came out.

Also, if a child template is inherited and a section of ' main ' is provided in the @section (' main ') @endsection, this overrides the ' main ' slice in the main template and only shows its own definition. Similar to object-oriented overrides.

After overriding the main template, then visit the sub-template to see

Because the @sectioin (' main ') @endsection in the child template provides the ' main ' slice, it overrides ' main ' in the parent.

Sometimes you may want to override the contents of a slice in a child template without overwriting the main template, so you can use @parent in the child template to display the tiles in the main template


@extends (' Layouts.master ') @section (' title ')    about page @endsection@section (' main ')    @parent    <p class= " Main "> About page" main content </p> @endsection

Access Child templates

The main content of the main template is displayed as well as the main content of the child template.

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.