本文概述
Blade是Laravel框架中强大的模板引擎。该Blade允许轻松使用模板引擎, 并且使语法编写非常简单。Blade模板引擎提供其自身的结构, 例如条件语句和循环。要创建Blade模板, 你只需要创建一个视图文件并以.blade.php扩展名而不是.php扩展名保存。Blade模板存储在/ resources / view目录中。使用Blade模板的主要优点是我们可以创建主模板, 该模板可以被其他文件扩展。
为什么选择Blade模板?
使用Blade模板的原因如下:
- 显示数据如果要打印变量的值, 则可以通过简单地将变量括在大括号内来进行打印。句法
{{$variable}};
在Blade模板中, 我们不需要在<?php echo $ variable;之间编写代码。 ?>。上面的语法等效于<?= $ variable?>。
- 三元运算符在Blade模板中, 三元运算符的语法可以写为:
{{ $variable or 'default value'}}
上面的语法等效于<?= isset($ variable)? $ variable:默认值?>
Blade模板控制语句
Blade模板引擎还提供laravel中的控制语句以及控制语句的快捷方式。
<html>
<body>
<font size='5' face='Arial'>
@if(($id)==1)
student id is equal to 1.
@else
student id is not equal to 1
@endif
</font>
</body>
</html>
输出量
Blade模板提供@unless指令作为条件语句。上面的代码等效于以下代码:
<html>
<body>
<font size='5' face='Arial'>
@unless($id==1)
student id is not equal to 1.
@endunless
</font>
</body>
</html>
@hasSection指令
Blade模板引擎还提供@hasSection指令, 该指令确定指定节是否具有任何内容。
让我们通过一个例子来理解。
<html>
<body>
<title>
@hasSection('title')
@yield('title') - App Name
@else
Name
@endif
</title>
</font>
</body>
</html>
输出量
Blade循环
Blade模板引擎提供诸如@ for, @ endfor, @ foreach, @ endforeach, @ while和@endwhile指令的循环。这些指令用于创建php循环等效语句。
@for循环
- 首先, 我们在resources / views目录中创建student.blade.php文件。
Student.blade.php
value of i :
@for($i=1;$i<11;$i++)
{{$i}}
@endfor
- 现在, 在PostController.php文件中添加以下代码。
public function display()
{
return view('student');
}
- 在web.php文件中添加路由。
Route::get('/details', 'PostController@display');
输出量
@foreach循环
- 首先, 我们在resources / views目录中创建student.blade.php文件。
@foreach($students as $students)
{{$students}}<br>
@endforeach
- 现在, 在PostController.php文件中添加以下代码。
public function display()
{
return view('student', ['students'=>['anisha', 'haseena', 'akshita', 'jyotika']]);
}
在上面的代码中, 我们将students数组传递给student.blade.php文件。
- 在web.php文件中添加路由。
Route::get('/details', 'PostController@display');
输出量
@while循环
- 首先, 我们在resources / views目录中创建student.blade.php文件。
@while(($i)<5)
srcmini
{{$i++}}
@endwhile
- 现在, 在PostController.php文件中添加以下代码。
public function display($i)
{
return view('student');
}
- 在web.php文件中添加路由。
Route::get('/details/{i}', 'PostController@display');
输出量
评论前必须登录!
注册