编程

在 Laravel 的分页中引入 URL 片段

133 2025-03-18 02:51:00

Laravel 的分页系统有一个强大的 fragment() 方法,允许你追加 URL 片段到分页链接中。当在导航过程中将用户引导到页面的特定区域时,此功能特别有用。  

$users = User::paginate(15)->fragment('users');

渲染时,分页链接将会自动在 URL 中使用 ‘#users’,将用户引导到页面的特定区域。

当处理多内容区域或复杂导航结构时,fragment() 方法尤其有用:

class ContentController extends Controller
{
    public function index(Request $request)
    {
        $activeSection = $request->section ?? 'recent';
 
        return View::make('content.index', [
            'posts' => Post::latest()
                ->paginate(10)
                ->fragment("section-{$activeSection}"),
            'activeSection' => $activeSection
        ]);
    }
}
// views/content/index.blade.php
<div id="section-{{ $activeSection }}">
    @foreach ($posts as $post)
        <!-- Post content -->
    @endforeach
    {{ $posts->links() }}
</div>

Laravel 会自动处理分页链接中的片段包含,生成类似 /posts?page=2#section-recent 的 URL。这种方法在用户浏览分页内容时保持上下文和滚动位置。