Laravel 5. Examples of middleware and views and the Blade template engine

黄舟
Release: 2023-03-15 21:54:01
Original
1744 people have browsed it

1. Middleware

Laravel's HTTP middleware provides a layer of filtering and protection for routing. Let's simulate using middleware to verify background login.

1. Create middleware

Go to the project directory in the cmd window and use the artisan command to create


php artisan make:middleware AdminLoginVerify
Copy after login

This will be in app/Http/ Middleware directory creation middleware AdminLoginVerify

Add verification logic in the handle() method of the AdminLoginVerify class:


<?php
namespace App\Http\Middleware;

use Closure;

class AdminLoginVerify
{
    public function handle($request, Closure $next)
    {
        if(!session(&#39;admin&#39;)){ // 如果没有登录则定向到登录页
            return redirect(&#39;admin/login&#39;);
        }
        return $next($request);
    }
}
Copy after login

ok, now Just create and define the login verification middleware AdminLoginVerify

2. Register the middleware

Find the protected $routeMiddleware attribute in the app/Http/Kernel.php file , append our AdminLoginVerify


protected $routeMiddleware = [
        &#39;auth&#39; => \App\Http\Middleware\Authenticate::class,
        &#39;auth.basic&#39; => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        &#39;can&#39; => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        &#39;guest&#39; => \App\Http\Middleware\RedirectIfAuthenticated::class,
        &#39;throttle&#39; => \Illuminate\Routing\Middleware\ThrottleRequests::class,
         // 自定义中间件
        &#39;adminLoginVerify&#39; => \App\Http\Middleware\AdminLoginVerify::class,
    ];
Copy after login

3. Add routing

Add routing in the app/Http/routes.php file:


// 后台首页路由、退出登录路由
Route::group([&#39;prefix&#39; => &#39;admin&#39;, &#39;namespace&#39; => &#39;Admin&#39;, &#39;middleware&#39; => &#39;adminLoginVerify&#39;], function(){
    Route::get(&#39;index&#39;, &#39;IndexController@index&#39;);
    Route::get(&#39;logout&#39;, &#39;IndexController@logout&#39;);
});

// 后台登录路由
Route::group([&#39;middleware&#39; => &#39;web&#39;], function(){
    Route::get(&#39;admin/login&#39;, &#39;Admin\IndexController@login&#39;);
});
Copy after login

This is the code of the Index controller in the background Admin directory:


<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

class IndexController extends Controller{

    // 后台首页
    public function index(){
        return &#39;<h1>欢迎你,&#39; . session(&#39;admin&#39;) . &#39;</h1>&#39;;
    }

    // 后台登录
    public function login(){
        session([&#39;admin&#39; => &#39;mingc&#39;]);
        return &#39;<h1>后台登录</h1>&#39;;
    }

    // 退出登陆
    public function logout(){
        session([&#39;admin&#39; => null]);
        return &#39;<h1>退出登录</h1>&#39;;
    }
}
Copy after login

4. Simulate login

Open the browser and visit the backend login page

Okay, visit the backend homepage

Now we log out

In the logged out state, accessing the home page will redirect you to the login page.

2. View

1. Render the view and allocate data

Method 1. Array key-value pair allocation


// 在控制器中
$data = array(
    &#39;title&#39; => &#39;Laravel&#39;,
    &#39;subTitle&#39; => &#39;高效快捷的PHP框架&#39;
);
return view(&#39;my_laravel&#39;, $data);

// 在模板中
<?php echo $title;?>
<?php echo $subTitle;?>
Copy after login

Method 2. With method chain allocation


// 在控制器中
return view(&#39;my_laravel&#39;)->with(&#39;title&#39;, &#39;Laravel&#39;)->with(&#39;subTitle&#39;, &#39;高效快捷的PHP框架&#39;);

// 在模板中(和上面的一样)
<?php echo $title;?>
<?php echo $subTitle;?>
Copy after login

Method 3. Using compact() function allocation


// 在控制器中
$data = array(
    &#39;title&#39; => &#39;Laravel&#39;,
    &#39;subTitle&#39; => &#39;高效快捷的PHP框架&#39;
);
$content = &#39;Laravel 5.2 在 5.1 基础上继续改进和优化,添加了许多新的功能特性...&#39;;
return view(&#39;my_laravel&#39;, compact(&#39;data&#39;, &#39;content&#39;));

// 在模板中(和前两个不太一样)
<?php echo $data[&#39;title&#39;] ; ?>
<?php echo $data[&#39;subTitle&#39;]; ?>
<?php echo $content; ?>
Copy after login

Among them, the first parameter my_laravel of the view() function is the view template name, which is in the resources/views view directory. The template file suffix is ​​.blade.php, using Blade Template engine.

3. Blade template engine

1. Output variables


// 输出单个变量
{{ $var }}

// 保留双大括号,编译为{{ var }}
@{{ var }}

// 可以输出默认值
{{ $var or &#39;我是默认值&#39; }}
{{ isset($var) ? $var : &#39;我是默认值&#39; }}

// Blade 注释
{{-- 这个注释不会输出到页面中 --}}

// 忽略字符实体化,输出 JS 或 HTML
{!! $var !!}
// 注: 因为 Blade 模板引擎默认对{{}}语句进行了 htmlentities 字符实体化,所以要输出JS或HTML代码时,应使用上述语法
Copy after login

2. Process control


// if 语句
@if($var == &#39;laravel&#39;)
    I am laravel
@elseif($var == &#39;yii&#39;)
    I am yii
@else
    I don’t know what I am.
@endif

// 循环
@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($array as $v)
    <p>我是数组成员 {{$v}}</p>
@endforeach

@forelse ($users as $v)
    <li>我的名字是{{ $v->name }}</li>
    @empty
    <p>我没有名字</p>
@endforelse

@while (true)
    <p>我一直在循环...</p>
@endwhile

// 可以嵌套
@for($i = 0; $i < 10; $i++)
    @if($i > 5)
        I am {{$i}} > 5
    @endif
@endfor
Copy after login

3. Template layout and subviews

@include File inclusion instructions.

@extends Template inheritance directive.

@yield                 Slice definition instructions (define the slice display position).

@section Slice provides instructions (defining the details of the slice).

@endsection The end tag of @section.

@Show @Section's ending mark, which provides sliced ​​content while displaying slices.

@parent The content tag of @section displays the slices of the parent template.

@include: Includes subviews, that is, file inclusion.

If multiple web pages in a website have common parts, such as top navigation, sidebar recommendations, and bottom copyright. In order to facilitate later maintenance and modification, you can extract the public parts of these web pages as separate files, put them in the common folder under the view directory, and name them top.balde.php, aside.blade.php and bottom.blade respectively. .php. Then in each of our view templates, you can use

@include(&#39;common.top&#39;) // 将顶部导航包含进来,其他公共部分同样处理。
Copy after login

If you need to pass variables, you can add parameters

 @include(&#39;common.top&#39;, [&#39;location&#39; => &#39;首页&#39;])
Copy after login

@extends: Template inheritance, inherit the parent template layout.

In the @include directive, it includes the extracted template part.

The @extends directive inherits an existing main template layout.

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


<!DOCTYPE html>
<html>
<head>
    <title>@yield(&#39;title&#39;, &#39;首页&#39;)</title>
</head>
<body>
    <p class="top">顶部</p>
    @yield(&#39;main&#39;)
    <p class="aside">侧栏</p>
    <p class="bottom">底部</p>
</body>
</html>
Copy after login

@yield( 'title', 'Home') directive defines the display of the page title in the tag </p><p>@yield('main') defines the display of the main content between the top and side columns. </p><p> </p><p>So where are the title and main content? This requires subtemplates. </p><p>Now we create a new sub-template child.blade.php in the view directory, the content is as follows: </p><p class="cnblogs_Highlighter"><br/></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;gutter:true;">@extends(&#39;layouts.master&#39;) @section(&#39;title&#39;) 关于页 @endsection @section(&#39;main&#39;) <p class="main">【关于页】主内容</p> @endsection</pre><div class="contentsignin">Copy after login</div></div><p>  </p><p> Define the pointer The routing of master main template view and child sub-template view, access the child sub-view in the browser</p><p><img src="https://img.php.cn/upload/article/000/000/194/7fe0e7a2b6084928ac5070d2f267c408-3.png" alt=""/></p><p></p><p>We see that the child sub-template inherits the master Contents of the main template: top, sidebar, bottom</p><p>同时,child 子模板也显示了自己的网页标题 “关于页” 和主内容 “【关于页】主内容”</p><p>这就是 master 主模板中切片定义者 @yield 和 child 子模板中切片提供者 @section@endsection 的功劳了。</p><p> </p><p><strong>@yield、@section: 定义切片和提供切片。</strong></p><p>@yield('main') 指令定义一段HTML切片,它指示了在这个位置显示一个名为'main'的切片</p><p>@section('main')@endsection 指令提供了一段HTML切片,它为@yield('main') 定义的'mian'切片提供了详细的内容。</p><p>那么有了切片的显示位置,有了切片的详细内容,就可以显示出一个详细的HTML切片了。</p><p> </p><p>应该注意到了,在主模板 master 中有这么一个</p><p class="cnblogs_Highlighter"><br/></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;gutter:true;">@yield(&#39;title&#39;, &#39;首页&#39;)</pre><div class="contentsignin">Copy after login</div></div><p>它指示了 'title' 切片的默认值。就是说,如果没有子模板继承主模板,或者继承了但没有用@section('title')@endsection 指令提供 'title' 切片,它将显示一个默认值 '首页' 。</p><p>现在,直接访问主模板看看</p><p><img src="https://img.php.cn/upload/article/000/000/194/7fe0e7a2b6084928ac5070d2f267c408-4.png" alt=""/></p><p>没错,没有子模板用 @section('title')@endsection 来提供标题, <span class="cnblogs_code">@yield(&#39;title&#39;, &#39;首页&#39;)</span> 显示了 'title' 切片的默认值 '首页'。</p><p>那么,主模板作为网站首页的话,它的主内容呢?如果要显示的话,难道又要写一个子模板来继承它,再用 @section@endsection 提供主内容?可不可以直接在主模板里写一个类似@yield(&#39;title&#39;, &#39;首页&#39;) 提供的默认值呢?</p><p>当然可以,下面来重写主模板</p><p class="cnblogs_Highlighter"><br/></p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:html;gutter:true;"><!DOCTYPE html> <html> <head> <title>@yield(&#39;title&#39;, &#39;首页&#39;)

顶部

@section('main')

【首页】主内容

@show

侧栏

底部

Copy after login

@section('main')@show 可以提供 'main' 切片并显示出来。

现在访问主模板看看,首页主内容出来了。

并且,如果有子模板继承,并用 @section('main')@endsection 中也提供了一段'main'切片的话,这将覆 盖 主模板中的 'main'切片,而只显示自己定义的。类似于面向对象的重写。

在重写了主模板后,再访问子模板看看

因为子模板中 @sectioin('main')@endsection 提供了'main'切片,所以覆盖了父级中的'main'。

有时候可能需要子模板中重写但不覆盖主模板的切片内容,那么可以在子模板中使用 @parent 来显示主模板中的切片


@extends(&#39;layouts.master&#39;)

@section(&#39;title&#39;)
    关于页
@endsection

@section(&#39;main&#39;)    @parent
    <p class="main">【关于页】主内容</p>
@endsection
Copy after login

 

访问子模板

显示子模板主内容的同时,也显示了主模板的主内容。

The above is the detailed content of Laravel 5. Examples of middleware and views and the Blade template engine. 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!