Laravel 的分頁系統包含一個強大的 fragment()
方法,允許您將 URL 片段附加到分頁鏈接。此功能在導航期間將用戶定向到頁面特定部分時尤其有用。
fragment()
方法與 Laravel 的分頁系統無縫集成:
$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) @endforeach {{ $posts->links() }} </div>
Laravel 會自動處理分頁鏈接中的片段包含,生成類似 /posts?page=2#section-recent
的 URL。這種方法在用戶瀏覽分頁內容時可以保持上下文和滾動位置。
以上是將URL片段納入Laravel的分頁的詳細內容。更多資訊請關注PHP中文網其他相關文章!