学习了blade模板引擎的一些基础知识,blade模板中使用PHP的语法,除了添加<?php ?>这种语法标记进行外,大多数PHP语法添加@开始 @end结束,如@php @endphp,@foreach @ednforeach。blade模板中 {{$name}}是输出转义后的变量,{!!$name!!}则原样输出变量,这样可以使得html标签不进行转义。然后就是blade模板中引入公共文件的@include,以及模板继承的@section。
<!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>
@php
$name='<span style="color:red;">这是一变量</span>';
$before='{';
$ofter='}';
@endphp
<div>使用{{$before}}{{$before}}$name{{$ofter}}{{$ofter}}来输出变量结果为:{{$name}}</div>
<br>
<div>使用{{$before}}!!$name!!{{$ofter}}来输出变量结果为:{!! $name !!}</div>
@php
$num=20;
@endphp
@if($num==8)
<div>$num等于8</div>
@elseif($num>8)
<div>$num大于8</div>
@else
<div>$num小于8</div>
@endif
<hr>
@php
$list=['小明','小刚','小红','小张'];
@endphp
使用foreach来循环数组
@foreach($list as $key =>$value)
<div>{{$key}}..{{$value}}</div>
@endforeach
<hr>
使用for来循环数组
@for($i=0;$i<count($list);$i++)
<div>{{$i}}..{{$list[$i]}}</div>
@endfor
</body>
</html>
这可以证明在blade模板中使用PHP语法的方法是以@开始,@end结束,虽然不知道是不是所有的PHP语句都可以这样写。
在blade模板中引入blade文件使用@include(''),文件路径在views往下,比如在我的views/admins/user/user.blade.php中引入views/admins/public/header.blade.php文件,只需要在user.blade.php文件指定位置添加@include('admins/public/header').
在blade模板中可以使用@section来进行模板的继承,首先需要在模板中配置@section('') @show 表明非继承区域,但事实上这个非继承区域的内容在子版中添加@parent也能继承过来。在子版中添加@section @endsection表明继承区域。
<!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>
<style>
table{
width: 100%;
text-align: center;
border-collapse:collapse;
margin:0 auto;
}
table th,table td{
border:1px solid black;
}
h3{
text-align: center;
width: 800px;
margin:0 auto;
}
header div{
background-color: #1d2124;
width: 100%;
height:30px;
text-align: center;
}
header div ul{
width: 80%;
height: 30px;
background-color: #1d2124;
margin:0 auto;
}
header div ul li{
list-style: none;
float: left;
margin:auto 10px;
height:30px;
line-height: 30px;
width:20%;
}
a{
text-decoration: none;
color:white;
}
</style>
</head>
<body>
@include('admins/public/header')
<div style="height: 800px;width: 80%;margin:0 auto;">
@section('user')
<p>这个是user.blade.php内容区域</p>
@show
</div>
@include('admins/public/footer')
</body>
</html>点击 "运行实例" 按钮查看在线实例
@extends('admins/user/user')
@section('user')
@parent @php //当添加上@parent的时候则会继承母版的内容,不添加的时候则不会继承母版的内容 @endphp
<p>这个是text.blader.php内容区域</p>
@endsection点击 "运行实例" 按钮查看在线实例

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号