首頁 > 後端開發 > php教程 > Laravel Blade Fragments的動態頁面更新

Laravel Blade Fragments的動態頁面更新

百草
發布: 2025-03-05 16:11:20
原創
273 人瀏覽過

Dynamic Page Updates with Laravel Blade Fragments

> 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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板