首页 >后端开发 >php教程 >Laravel Blade Fragments的动态页面更新

Laravel Blade Fragments的动态页面更新

百草
百草原创
2025-03-05 16:11:20276浏览

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