Laravel 5.6 视图用Blade语法传递变量和流程控制if 语句和循环语句

时间:2023-12-19 20:34:08

Laravel5.6 视图用Blade语法传递变量和流程控制if 语句和循环语句

Laravel 的 View 部分是内置了两套输出系统:直接输出和使用 Blade 引擎“编译”后输出,默认情况下它们通过文件名后缀来选择:.blade.php 后缀的认为是模板视图文件,其他的 .php 文件按照 PHP 本身的方式执行。虽然 Blade 模板文件中也可以随意嵌入 PHP 代码,但如果并没有使用,系统还去进行语法解析和替换也是没有必要的,这样可以提高效率。

Laravel使用的是Blade视图引擎
Blade视图文件使用.blade.php
传递:变量到视图
显示:通过两个{{}}花括号包裹起来来显示

可以使用@if @elseif @else @endif 来构造if语句
这些指令的功能和php对应的功能一样
switch语句和for语句

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/ Route::get('/', function () {
return view('welcome');
}); Route::get('/helloworld',function(){
//return "Hello World! 这个是不使用模板 自定义字符串";
return view('helloworld',['name'=>'Laravel Zero Basic Quickstart','title'=>'This is Title','records'=>0]);
}
); Route::get('/bootstrap',function(){
return view('bootstrap');
});

  helloworld.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>{{$title}}</title>
</head>
<body>
<div class="jumbotron text-center">
<h1>{{$name}}</h1>
<p>Video Course</p>
</div>
<div class="container"> <div class="row">
<div class="col-sm-8">
<div class="card">
<div class="card-header">Course List</div>
<div class="card-body">Content
@if($records ===1)
I have one records
@elseif($records>1)
I have multiple records
@else
I don't have any records
@endif <br/>
@for($i=0;$i<10;$i++)
The current value is {{$i}}<br/>
@endfor
</div>
</div>
</div> <div class="col-sm-4">
<div class="card-header">Course Intro</div>
<div class="card-body">Laravel Quickstart</div>
<div class="card-footer">Footer</div>
</div> </div> </div><!--END container--> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>