批改状态:合格
老师批语:现在还在写模板的作业, 要加油了... 作业完成的很认真
练习一下blade模板的语法。如:变量渲染、foreach、if...else...、include、section
新建控制器文件Home.php,代码如下:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Home extends Controller
{
public function index(){
$data=[
'bt'=>'文章标题测试',
'nr'=>'文章内容区文章内容区文章内容区文章内容区文章内容区文章内容区文章内容区文章内容区文章内容区文章内容区',
'zz'=>['name'=>'Tommy','sex'=>'Boy','age'=>18]
];
return view('/index',$data);
}
}接下来先演示下foreach在blade模板引擎中的用法:
// foreach 循环
@foreach ($staffssss as $staffsss)
{{ $talk->name }} ({{ $talk->email }} <br>
@endforeach视图index.blade.php代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>我的网站</title>
</head>
<body>
<h1>{{$bt}}</h1>
<h4 style="width: 600px;">{{$nr}}</h4>
@foreach($zz as $k=>$v)
<span>{{$v}}</span><br>
@endforeach
</body>
</html>运行后效果如下图所示:

接下来演示一下if else 在模板引擎中的用法:
把控制器文件Home.php修改为如下代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Home extends Controller
{
public function index(){
//注意传过去的$data必须为一个数组
$data=[
'score'=>88
];
return view('/index',$data);
}
}index.blade.php代码如下:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>我的网站</title> </head> <body> @if ($score>=90) <h1>你是最棒的!</h1> @elseif ($score>=80 && $score<90) <h1>继续保持努力!</h1> @elseif ($score>=60 && $score<80) <h1>加油,相信你自己!</h1> @else ($score<60) <h1>不努力怎么知道自己是最好的,加油吧!</h1> @endif </body> </html>
运行后效果如下图所示:

include在上一篇文章示例过了,这里对section的用法实例
新建test.blade.php文件,把它定义为父级模板文件,代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>我的网站</title>
</head>
<body>
<h1>blade模板使用</h1>
{{--注意在父级页面是show结尾,子页面是endsection结尾--}}
@section('workspace')
<h2>我是指定位置插入的一条内容</h2>
@show
</body>
</html>将视图文件index.blade.php(子页面)代码修改为:
@extends('test')
{{--extends是继承某个视图文件--}}
{{--在blade模板引擎中写注释可以这样的方式去写--}}
@php
//也可以这样写注释,用户端是看不到的,不会解析到前端代码中;
@endphp
@section('workspace')
{{--需要和父级模板的命名一致--}}
{{--如果想继承父级的内容,加一个@parent即可,都是想插入到哪里就加到哪里去--}}
@parent
<div style="width: 100%;height: 200px;background: orangered"></div>
@endsection结果如下图所示:

注意section在父级页面是show结尾,子页面是endsection结尾。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号