> Laravel刀片片段提供了一種簡化的部分頁面更新方法,非常適合HTMX或Turbo等框架。 該服務器端解決方案增強了交互性,而無需犧牲Laravel的易用性。
>利用葉片片段
這是定義和使用片段的一個基本示例:
<!-- Blade template --> @fragment('notification-list') <div class="notifications"> @foreach($notifications as $notification) <div class="alert"> {{ $notification->message }} </div> @endforeach </div> @endfragment <!-- Controller --> return view('dashboard')->fragment('notification-list');現實世界應用程序:實時通知系統
> >讓我們用實時通知系統說明:
對應的模板結構:
<?php namespace App\Http\Controllers; use App\Models\Notification; use Illuminate\Http\Request; class NotificationController extends Controller { public function store(Request $request) { $notification = Notification::create([ 'user_id' => auth()->id(), 'message' => $request->message, 'type' => $request->type ]); if ($request->hasHeader('HX-Request')) { return view('notifications.index', [ 'notifications' => auth()->user()->notifications()->latest()->get() ])->fragmentIf( $request->hasHeader('HX-Request'), 'notification-list' ); } return back(); } public function clear(Request $request) { auth()->user()->notifications()->delete(); return view('notifications.index', [ 'notifications' => collect() ])->fragment('notification-list'); } }
>這表明了刀片片段如何提供一種清潔,有效的方法來更新頁面的部分,並與現代Web開發的最佳實踐完全保持一致。 與漸進式增強技術的集成使其成為Laravel生態系統中強大的工具。
<div class="container"> @fragment('notification-list') <div class="notification-wrapper"> @forelse($notifications as $notification) <div class="alert alert-{{ $notification->type }}"> {{ $notification->message }} {{ $notification->created_at->diffForHumans() }} </div> @empty <p>No notifications</p> @endforelse </div> @endfragment </div>
以上是Laravel Blade Fragments的動態頁面更新的詳細內容。更多資訊請關注PHP中文網其他相關文章!