本文讲解如何利用 laravel 分页器的 `currentpage()` 方法,精准控制首页(page=1)与后续分页页(page=2+)的样式逻辑,避免首页专属布局(如置顶卡片、双栏展示等)错误复用到第二页及以后。
在 Laravel 博客类项目中,常需为首页设计差异化内容结构:例如首篇文章使用大图横幅(
解决核心在于动态判断当前分页页码。Laravel 的 LengthAwarePaginator 实例(即 $posts)提供了 currentPage() 方法,返回当前请求的页码(整数,默认为 1)。我们据此条件化渲染:
@include('posts.__header') @if ($posts->count()) @if ($posts->count() > 1) @if($posts->currentPage() === 1) @endif @foreach ($posts->skip($posts->currentPage() === 1 ? 3 : 0) as $post)
@endforeach @endif {{ $posts->links() }} @else No posts match your search. Please check back later.
@endif
⚠️ 关键注意事项:
通过这一模式,你既能维持首页的视觉层次与信息优先级,又能让 page=2+ 回归简洁、统一的三栏列表,实现语义清晰、维护性强的分页体验。