主要用於簡化重複的程式碼,藉由母檔案的方式讓其他頁面繼承共同程式碼
1.首先新增一個資料夾叫layouts並新增一個app.blade.php,接著在<body>內建立一個<div>
這時候我們會使用@yield,利用它將index的檔案放入到yield裡面去
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>電商網站</title>
</head>
<body>
<div>
@yield('content')
</div>
</body>
</html>
2.接著我們要做partial_view,首先我們先新增一個nav.blade.php,並把index的導覽頁貼上
3.由於我們每一頁都需要有這個商品列表的導覽頁,所以我們要到app.blade裡面去做引入,接著在<div>上方使用@include
這時候就會告訴系統說,我要取得在layouts資料夾裡面的nav這個檔案,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>電商網站</title>
</head>
<body>
@include('layouts.nav')
<div>
@yield('content')
</div>
</body>
</html>
4.接著要讓資料完整秀出,這時候我們要在index裡面加上@extends引用layouts.app的檔案,並增加@section將HTML程式碼放入
@extends('layouts.app')
@section('content')
<link rel="stylesheet" href="css/style.css">
<h2>商品列表</h2>
<img src="<https://image.cache.storm.mg/styles/smg-800x533-fp/s3/media/image/2017/01/09/20170109-101556_U7298_M236105_ac3e.png?itok=f9rMALcc>" alt="">
<table>
<thead>
<tr>
<td>標題</td>
<td>內容</td>
<td>價格</td>
<td></td>
</tr>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
@if ( $product->id ==1)
<td class="special-text">{{ $product ->title }}</td>
@else
<td>{{ $product ->title }}</td>
@endif
<td>{{ $product ->content }}</td>
<td>{{ $product ->price }}</td>
<td><input class="check_product" type="button" value="確認商品數量" data-id="{{$product->id }}"></td>
</tr>
@endforeach
</tbody>
</table>
<script src="<https://code.jquery.com/jquery-3.6.0.min.js>"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
<script>
$('.check_product').on('click',function(){
$.ajax({
method:'POST',
url: '/products/check-product',
data: {id: $(this).data('id')}
})
.done(function(response){
if(response){
alert('商品數量充足')
}
else{
alert('商品數量不夠')
}
})
})
</script>
@endsection
<aside> 💡 未來有越來越重複的程式碼就可以利用這個方式進行簡化處理
</aside>