梦入琼楼寒有月,行过石树冻无烟

Laravel Blade

在Laravel Blade内,官方所提供了一个简洁且优雅的前端模板引擎,他允许你在blade.php文件内写入html以及PHP代码,他因为所有Blade语法都会被编译成正常的PHP代码并缓存,所以速度会稍微快那么一点。除非在此修改,某则Blade模板将不会在此进行编译,在一般的情况下都会将会存放在/resouces/views目录内。

模板继承

在Laravel blade内,模板继承是常见的一种,这种写法在Laravel oauth内使用中,其语法和隔壁Thymeleaf模板引擎更加的简单,其中主要分为定义@section以及@yield显示等。Laravel内,以“@”为开头的将会被称之为“指令”,通过指令我们可以实现继承、循环、判断等。

@section……@show and @yield

index

1
2
3
4
5
6
7
8
9
10
11
{{-- index.blade.php --}}
<html>
<head>
<title>index - @yield('title')</title>
</head>
<body>
@section('h1')
<p>Hello,world!</p>
@show
</body>
</html>

inbar

1
2
3
4
{{inbar.blade.php}}
@extends('index')
@section('title','inbar')
@section('h1','Hello,inbar')

在模板继承中,我们主要使用了@yield以及@section指令,其中@yield 用于显示内容 ,而 @section 将会被用于定义一部分内容。所以在index.blade.php内,在<title>标签中使用了@yield即显示”title”内容,所以在inbar.blade.php内容由”@section”所指定定义了title -> inbar所以与index、inbar所组合后的index- inbar的标题。

而在index.blade.php@section所定义的将会被@section('h1','Hello,inbar')所替换,而以后我们将会介绍如何保留@section所替换掉的内容。

@section……@parent……@endsection

在上述一章中我们介绍了@section……@show……@yield,而此次我们将会增加一个,@parent以及@endsection,这两个指令分别是保留所替换掉的@section以及结束本次替换字段。

index

1
2
3
4
5
6
7
8
9
10
11
{{-- index.blade.php --}}
<html>
<head>
<title>index - @yield('title')</title>
</head>
<body>
@section('h1')
<p>Hello,world!</p>
@show
</body>
</html>

inbar

1
2
3
4
5
6
7
{{-- inbar.blade.php --}}
@extends('index')
@section('title','inbar')
@section('h1')
@parent
<p>Hello,inbar!</p>
@endsection

本文我们通过使用 @parent 来保留使用 @section 指令所替换或覆盖的内容,所以通过使用此指令将会保留覆盖的内容。而@section……@endsection将会使用@section……@endsection来结束替换指令,而不是根据上述使用的@section('h1','Hello,inbar')

@show 与 @endsection

根据官方的解释是在同一模板定义@section时,使用@show,而在子模板即“扩展布局”中使用@endsection作为结尾。在本文同一模板即index.blade.php内,写入任何信息即“同一模板”,而如果在除了以index.blade.php外的则是子模板。

@extends

通过上述介绍,读者得知@extends('index')用于引入和扩展视图扩展到另外一个视图内,即将inbar.blade.php内使用@extends('index')来引入index.blade.php文件。而{{-- code --}}将会用于注释,这与html所使用的<!-- code -->同意。

with …… title (composer)

在Laravel中,我们可以通过使用composer来进行数据的传递以及获取和定义,我们可以通过使用此方法来进行视图(view)、控制器(controller)进行传递。

web.php

1
2
3
Route::get('/', function () {
return view('inbar')->with('title', 'Hello,world');
});

inbar.blade.php

1
{{$title}}

条件与循环语句

条件语法

@php …… @endphp

在众多的教材以及文档中都会教给大家一段 Laravel Blade引擎模板,所以本文将会以一个i前后顺序来介绍@php……@endphp指令:

1
2
3
4
5
6
7
@if (count($value) === 1)
……
@elseif (count($value) === 0)
……
@else
……
@endif

@if……@elseif……@else……@endif

通过上述code你可能会更加疑惑$value是怎么传过去或怎么定义的,此时你会通过使用控制器、路由、视图中进行定义或传入,也许你可以通过使用with来通过路由进行传递,本文我们告知下最为简单的演示@php……@endphp指令的作用。

1
2
3
4
5
6
7
8
9
10
@php
$var = array('1','2')
@endphp
@if (count($var) === 1)
一个数组
@elseif (count($var) >= 2)
大于两个数组
@else
都不是
@endif

我们通过以上code和流程图的演示,可以明显的表示出@php……@endphp来定义一个并富有两个数组分别为“1、2”。经过判断语法是大于两个数组的,所以自然而然的输出为“大于两个数组”

循环语句

@for……@foreach


在Laravel blade模板引擎中,不仅仅为我们提供了一个条件指令@if……@elseif……@else……@endif,自然而然的为开发者提供了一个简单的循环指令@for……@foreach

1
2
3
@for($i = 0;$i < 10;$i++)
共输出 {{$i}} 次<br>
@endfor
⬅️ Go back