[英]Custom pagination view in Laravel 5
Laravel 4.2可以選擇在app/config/view.php
中指定自定義視圖,例如:
/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
'pagination' => 'pagination_slider-alt'
這至少在Laravel 5中消失了view.php
。
有沒有辦法在Laravel 5中復制此行為?
在Laravel 5.3+ 中使用
$users->links('view.name')
在Laravel 5.0 - 5.2而不是
$users->render()
用
@include('pagination.default', ['paginator' => $users])
視圖/分頁/default.blade.php
@if ($paginator->lastPage() > 1)
<ul class="pagination">
<li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
<a href="{{ $paginator->url(1) }}">Previous</a>
</li>
@for ($i = 1; $i <= $paginator->lastPage(); $i++)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endfor
<li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
<a href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
</li>
</ul>
@endif
就是這樣。
如果您有很多頁面,請使用此模板:
視圖/分頁/limit_links.blade.php
<?php
// config
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>
@if ($paginator->lastPage() > 1)
<ul class="pagination">
<li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
<a href="{{ $paginator->url(1) }}">First</a>
</li>
@for ($i = 1; $i <= $paginator->lastPage(); $i++)
<?php
$half_total_links = floor($link_limit / 2);
$from = $paginator->currentPage() - $half_total_links;
$to = $paginator->currentPage() + $half_total_links;
if ($paginator->currentPage() < $half_total_links) {
$to += $half_total_links - $paginator->currentPage();
}
if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
$from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
}
?>
@if ($from < $i && $i < $to)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endif
@endfor
<li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
<a href="{{ $paginator->url($paginator->lastPage()) }}">Last</a>
</li>
</ul>
@endif
對於 Laravel 5.3(可能在其他 5.X 版本中),將自定義分頁代碼放在您的視圖文件夾中。
資源/視圖/分頁/default.blade.php
@if ($paginator->hasPages())
<ul class="pagination">
{{-- Previous Page Link --}}
@if ($paginator->onFirstPage())
<li class="disabled"><span>«</span></li>
@else
<li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">«</a></li>
@endif
{{-- Pagination Elements --}}
@foreach ($elements as $element)
{{-- "Three Dots" Separator --}}
@if (is_string($element))
<li class="disabled"><span>{{ $element }}</span></li>
@endif
{{-- Array Of Links --}}
@if (is_array($element))
@foreach ($element as $page => $url)
@if ($page == $paginator->currentPage())
<li class="active"><span>{{ $page }}</span></li>
@else
<li><a href="{{ $url }}">{{ $page }}</a></li>
@endif
@endforeach
@endif
@endforeach
{{-- Next Page Link --}}
@if ($paginator->hasMorePages())
<li><a href="{{ $paginator->nextPageUrl() }}" rel="next">»</a></li>
@else
<li class="disabled"><span>»</span></li>
@endif
</ul>
@endif
然后從主視圖文件中調用這個分頁視圖文件作為
{{ $posts->links('pagination.default') }}
根據需要更新分頁/default.blade.php
它也適用於 8.x 版本。
在 Laravel 5 中自定義分頁基於演示者(類)而不是視圖。
假設在你的路由代碼中你有
$users = Users::paginate(15);
在 L4 中,你曾經在視圖中做這樣的事情:
$users->appends(['sort' => 'votes'])->links();
在 L5 中,您改為:
$users->appends(['sort' => 'votes'])->render();
render()
方法接受一個Illuminate\\Contracts\\Pagination\\Presenter
實例。 您可以創建一個實現該契約的自定義類並將其傳遞給render()
方法。 請注意, Presenter
是一個interface ,而不是一個類,因此您必須實現它,而不是擴展它。 這就是您收到錯誤的原因。
或者,您可以擴展 Laravel 分頁器(以便使用其分頁邏輯),然后將現有的分頁實例( $users->...
)傳遞給您的擴展類構造函數。 這確實是我基於 Laravel 提供的 Bootstrap 演示器創建自定義Zurb Foundation演示器所做的工作。 它使用所有 Laravel 分頁邏輯並且只覆蓋渲染方法。
使用我的自定義演示者,我的視圖如下所示:
with(new \Stolz\Laravel\Pagination($users->appends(['sort' => 'votes'])))->render();
我定制的分頁演示者是:
<?php namespace Stolz\Laravel;
use Illuminate\Pagination\BootstrapThreePresenter;
class Pagination extends BootstrapThreePresenter
{
/**
* Convert the URL window into Zurb Foundation HTML.
*
* @return string
*/
public function render()
{
if( ! $this->hasPages())
return '';
return sprintf(
'<ul class="pagination" aria-label="Pagination">%s %s %s</ul></div>',
$this->getPreviousButton(),
$this->getLinks(),
$this->getNextButton()
);
}
/**
* Get HTML wrapper for disabled text.
*
* @param string $text
* @return string
*/
protected function getDisabledTextWrapper($text)
{
return '<li class="unavailable" aria-disabled="true"><a href="javascript:void(0)">'.$text.'</a></li>';
}
/**
* Get HTML wrapper for active text.
*
* @param string $text
* @return string
*/
protected function getActivePageWrapper($text)
{
return '<li class="current"><a href="javascript:void(0)">'.$text.'</a></li>';
}
/**
* Get a pagination "dot" element.
*
* @return string
*/
protected function getDots()
{
return $this->getDisabledTextWrapper('…');
}
}
而在Laravel 4.2 中我會使用:
{{ $users->links('view.name') }}
在Laravel 5 中,您可以使用以下內容復制上述內容:
@include('view.name', ['object' => $users])
現在,在包括視圖, $object
都提供了分頁方法,如currentPage()
lastPage()
perPage()
等。
您可以在http://laravel.com/docs/5.0/pagination查看所有可用的方法
在5.5
links()
被替換為render()
,它的工作方式類似。 [官方文件]
代替
{{ $replies->links() }}
和
{{ $replies->render("pagination::default") }}
以下命令將在resources/views/vendor/pagination
生成分頁模板
artisan vendor:publish --tag=laravel-pagination
artisan vendor:publish
在任何視圖文件(刀片文件)中,您都可以使用這些模板,例如:
{{ $replies->render("pagination::default") }}
{{ $replies->render("pagination::bootstrap-4") }}
{{ $replies->render("pagination::simple-bootstrap-4") }}
{{ $replies->render("pagination::semantic-ui") }}
如果有人需要,Laravel 5 附帶了Bootstrap 4 分頁器。
首先創建一個新的服務提供者。
php artisan make:provider PaginationServiceProvider
在register
方法中,將閉包傳遞給 Laravel 的 paginator 類,該類創建並返回新的演示者。
<?php
namespace App\Providers;
use Illuminate\Pagination\BootstrapFourPresenter;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;
class PaginationServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
Paginator::presenter(function($paginator)
{
return new BootstrapFourPresenter($paginator);
});
}
}
在config/app.php
注冊新的提供者
'providers' => [
//....
App\Providers\PaginationServiceProvider::class,
]
也許為時已晚,但我想分享我制作的另一個自定義分頁模板,該模板創建了第一個/下一個和最后一個/上一個鏈接。 當用戶已經在第一頁/最后一頁時,它也會隱藏鏈接。
(可選)還可以確定鏈接間隔(當前頁面前后的鏈接數)
用法示例:
@include('pagination', ['paginator' => $users])
或者
@include('pagination', ['paginator' => $users, 'interval' => 5])
這是要點: https : //gist.github.com/carloscarucce/33f6082d009c20f77499252b89c35dea
和代碼:
@if (isset($paginator) && $paginator->lastPage() > 1)
<ul class="pagination">
<?php
$interval = isset($interval) ? abs(intval($interval)) : 3 ;
$from = $paginator->currentPage() - $interval;
if($from < 1){
$from = 1;
}
$to = $paginator->currentPage() + $interval;
if($to > $paginator->lastPage()){
$to = $paginator->lastPage();
}
?>
<!-- first/previous -->
@if($paginator->currentPage() > 1)
<li>
<a href="{{ $paginator->url(1) }}" aria-label="First">
<span aria-hidden="true">«</span>
</a>
</li>
<li>
<a href="{{ $paginator->url($paginator->currentPage() - 1) }}" aria-label="Previous">
<span aria-hidden="true">‹</span>
</a>
</li>
@endif
<!-- links -->
@for($i = $from; $i <= $to; $i++)
<?php
$isCurrentPage = $paginator->currentPage() == $i;
?>
<li class="{{ $isCurrentPage ? 'active' : '' }}">
<a href="{{ !$isCurrentPage ? $paginator->url($i) : '#' }}">
{{ $i }}
</a>
</li>
@endfor
<!-- next/last -->
@if($paginator->currentPage() < $paginator->lastPage())
<li>
<a href="{{ $paginator->url($paginator->currentPage() + 1) }}" aria-label="Next">
<span aria-hidden="true">›</span>
</a>
</li>
<li>
<a href="{{ $paginator->url($paginator->lastpage()) }}" aria-label="Last">
<span aria-hidden="true">»</span>
</a>
</li>
@endif
</ul>
@endif
只需將以下腳本放在您的頁面中:
<script>
$('.pagination li').addClass('page-item');
$('.pagination li a').addClass('page-link');
$('.pagination span').addClass('page-link');
</script>
優點:節省服務器 CPU,無需在您的應用程序中進行調整。
Laravel 5.2 為此使用演示器。 您可以創建自定義演示者或使用預定義的演示者。 Laravel 5.2 使用BootstrapThreePrensenter
開箱即用,但很容易使用BootstrapFroutPresenter
或任何其他自定義演示器。
public function index()
{
return view('pages.guestbook',['entries'=>GuestbookEntry::paginate(25)]);
}
在您的刀片模板中,您可以使用以下公式:
{!! $entries->render(new \Illuminate\Pagination\BootstrapFourPresenter($entries)) !!}
為了創建自定義演示者,我建議觀看Codecourse 的視頻。
如果你想美化你的分頁外觀,我使用 bootstrap 中的類來使它更簡單易行
@if ($students->lastPage() > 1)
<ul class="pagination ml-auto">
<li class="{{ ($students->currentPage() == 1) ? ' disabled' : '' }} page-item">
<a class=" page-link " href="{{ $students->url(1) }}" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>
@for ($i = 1; $i <= $students->lastPage(); $i++)
<li class="{{ ($students->currentPage() == $i) ? ' active' : '' }} page-item">
<a class=" page-link " href="{{ $students->url($i) }}">{{ $i }}</a>
</li>
@endfor
<li class="{{ ($students->currentPage() == $students->lastPage()) ? ' disabled' : '' }} page-item">
<a href="{{ $students->url($students->currentPage()+1) }}" class="page-link" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>
</ul>
@endif
我正在使用Laravel 5.8 。 任務是使分頁像下一個http://some-url /page-N而不是http://some-url ?page=N 。 它不能通過編輯 /resources/views/vendor/pagination/blade-name-here.blade.php 模板來完成(它可以通過php artisan vendor:publish --tag=laravel-pagination命令生成)。 在這里,我不得不擴展核心類。
我的模型使用了數據庫實例的分頁方法,如下所示:
$essays = DB::table($this->table)
->select('essays.*', 'categories.name', 'categories.id as category_id')
->join('categories', 'categories.id', '=', 'essays.category_id')
->where('category_id', $categoryId)
->where('is_published', $isPublished)
->orderBy('h1')
->paginate( // here I need to extend this method
$perPage,
'*',
'page',
$page
);
讓我們開始吧。 paginate()方法放置在\\Illuminate\\Database\\Query\\Builder 中並返回Illuminate\\Pagination\\LengthAwarePaginator對象。 LengthAwarePaginator擴展了Illuminate\\Pagination\\AbstractPaginator ,它有公共函數 url($page)方法,需要擴展:
/**
* Get the URL for a given page number.
*
* @param int $page
* @return string
*/
public function url($page)
{
if ($page <= 0) {
$page = 1;
}
// If we have any extra query string key / value pairs that need to be added
// onto the URL, we will put them in query string form and then attach it
// to the URL. This allows for extra information like sortings storage.
$parameters = [$this->pageName => $page];
if (count($this->query) > 0) {
$parameters = array_merge($this->query, $parameters);
}
// this part should be overwrited
return $this->path
. (Str::contains($this->path, '?') ? '&' : '?')
. Arr::query($parameters)
. $this->buildFragment();
}
分步指南(我從這篇不錯的文章中獲取的部分信息):
2.1 CustomConnection.php文件:
namespace App\Extended;
use \Illuminate\Database\MySqlConnection;
/**
* Class CustomConnection
* @package App\Extended
*/
class CustomConnection extends MySqlConnection {
/**
* Get a new query builder instance.
*
* @return \App\Extended\CustomQueryBuilder
*/
public function query() {
// Here core QueryBuilder is overwrited by CustomQueryBuilder
return new CustomQueryBuilder(
$this,
$this->getQueryGrammar(),
$this->getPostProcessor()
);
}
}
2.2 CustomLengthAwarePaginator.php 文件 - 該文件包含需要覆蓋的主要信息部分:
namespace App\Extended;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
/**
* Class CustomLengthAwarePaginator
* @package App\Extended
*/
class CustomLengthAwarePaginator extends LengthAwarePaginator
{
/**
* Get the URL for a given page number.
* Overwrited parent class method
*
*
* @param int $page
* @return string
*/
public function url($page)
{
if ($page <= 0) {
$page = 1;
}
// here the MAIN overwrited part of code BEGIN
$parameters = [];
if (count($this->query) > 0) {
$parameters = array_merge($this->query, $parameters);
}
$path = $this->path . "/{$this->pageName}-$page";
// here the MAIN overwrited part of code END
if($parameters) {
$path .= (Str::contains($this->path, '?') ? '&' : '?') . Arr::query($parameters);
}
$path .= $this->buildFragment();
return $path;
}
}
2.3 CustomQueryBuilder.php 文件:
namespace App\Extended;
use Illuminate\Container\Container;
use \Illuminate\Database\Query\Builder;
/**
* Class CustomQueryBuilder
* @package App\Extended
*/
class CustomQueryBuilder extends Builder
{
/**
* Create a new length-aware paginator instance.
* Overwrite paginator's class, which will be used for pagination
*
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
protected function paginator($items, $total, $perPage, $currentPage, $options)
{
// here changed
// CustomLengthAwarePaginator instead of LengthAwarePaginator
return Container::getInstance()->makeWith(CustomLengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}
在/config/app.php 中需要更改 db provider:
'providers' => [ // comment this line // illuminate\\Database\\DatabaseServiceProvider::class, // and add instead: App\\Providers\\CustomDatabaseServiceProvider::class,
在您的控制器(或從數據庫接收分頁數據的其他地方)中,您需要更改分頁設置:
// here are paginated results $essaysPaginated = $essaysModel->getEssaysByCategoryIdPaginated($id, config('custom.essaysPerPage'), $page); // init your current page url (without pagination part) // like http://your-site-url/your-current-page-url $customUrl = "/my-current-url-here"; // set url part to paginated results before showing to avoid // pagination like http://your-site-url/your-current-page-url/page-2/page-3 in pagination buttons $essaysPaginated->withPath($customUrl);
在您的視圖中添加分頁鏈接(/resources/views/your-controller/your-blade-file.blade.php),如下所示:
<nav> {!!$essays->onEachSide(5)->links('vendor.pagination.bootstrap-4')!!} </nav>
請享用! :) 您的自定義分頁現在應該可以工作了
嗨,我的分頁代碼:在刀片中使用 @include('pagination.default', ['paginator' => $users])
視圖/分頁/default.blade.php
@if ($paginator->lastPage() > 1)
si la pagina actual es distinto a 1 y hay mas de 5 hojas muestro el boton de 1era hoja --> if actual page is not equals 1, and there is more than 5 pages then I show first page button --> @if ($paginator->currentPage() != 1 && $paginator->lastPage() >= 5) << @endif
<!-- si la pagina actual es distinto a 1 muestra el boton de atras -->
@if($paginator->currentPage() != 1)
<li>
<a href="{{ $paginator->url($paginator->currentPage()-1) }}" >
<
</a>
</li>
@endif
<!-- dibuja las hojas... Tomando un rango de 5 hojas, siempre que puede muestra 2 hojas hacia atras y 2 hacia adelante -->
<!-- I draw the pages... I show 2 pages back and 2 pages forward -->
@for($i = max($paginator->currentPage()-2, 1); $i <= min(max($paginator->currentPage()-2, 1)+4,$paginator->lastPage()); $i++)
<li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endfor
<!-- si la pagina actual es distinto a la ultima muestra el boton de adelante -->
<!-- if actual page is not equal last page then I show the forward button-->
@if ($paginator->currentPage() != $paginator->lastPage())
<li>
<a href="{{ $paginator->url($paginator->currentPage()+1) }}" >
>
</a>
</li>
@endif
<!-- si la pagina actual es distinto a la ultima y hay mas de 5 hojas muestra el boton de ultima hoja -->
<!-- if actual page is not equal last page, and there is more than 5 pages then I show last page button -->
@if ($paginator->currentPage() != $paginator->lastPage() && $paginator->lastPage() >= 5)
<li>
<a href="{{ $paginator->url($paginator->lastPage()) }}" >
>>
</a>
</li>
@endif
</ul>
這是 Laravel 5、Bootstrap 4 和沒有 Blade 語法的一個(對於那些發現它非常難以閱讀的人)。
使用,而不是:
{!! $users->render() !!}
用:
@include('partials/pagination', ['paginator' => $users])
其中partials/pagination
是您的刀片模板文件,其中粘貼了以下內容。
// Number of links to show. Odd numbers work better
$linkCount = 7;
$pageCount = $paginator->lastPage();
if ($pageCount > 1)
{
$currentPage = $paginator->currentPage();
$pagesEitherWay = floor($linkCount / 2);
$paginationHtml = '<ul class="pagination">';
// Previous item
$previousDisabled = $currentPage == 1 ? 'disabled' : '';
$paginationHtml .= '<li class="page-item '.$previousDisabled.'">
<a class="page-link" href="'.$paginator->url($currentPage - 1).'" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>';
// Set the first and last pages
$startPage = ($currentPage - $pagesEitherWay) < 1 ? 1 : $currentPage - $pagesEitherWay;
$endPage = ($currentPage + $pagesEitherWay) > $pageCount ? $pageCount : ($currentPage + $pagesEitherWay);
// Alter if the start is too close to the end of the list
if ($startPage > $pageCount - $linkCount)
{
$startPage = ($pageCount - $linkCount) + 1;
$endPage = $pageCount;
}
// Alter if the end is too close to the start of the list
if ($endPage <= $linkCount)
{
$startPage = 1;
$endPage = $linkCount < $pageCount ? $linkCount : $pageCount;
}
// Loop through and collect
for ($i = $startPage; $i <= $endPage; $i++)
{
$disabledClass = $i == $currentPage ? 'disabled' : '';
$paginationHtml .= '<li class="page-item '.$disabledClass.'">
<a class="page-link" href="'.$paginator->url($i).'">'.$i.'</a>
</li>';
}
// Next item
$nextDisabled = $currentPage == $pageCount ? 'disabled' : '';
$paginationHtml .= '<li class="page-item '.$nextDisabled.'">
<a class="page-link" href="'.$paginator->url($currentPage + 1).'" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>';
$paginationHtml .= '</ul>';
echo $paginationHtml;
}
除了@MantasD 的答案,我想提供全面的定制 Laravel 分頁。 假設使用 Laravel 5.2 和以下包含的視圖:
@include('pagination.default', ['pager' => $users])
特征
default.blade.php
@if($pager->lastPage() != 1)
<ul class="pagination">
@unless($pager->currentPage() < 3)
<li class="paginate_button previous">
<a href="{{ $pager->url(1) }}" title="First Page"><i class="fa fa-angle-double-left"></i></a>
</li>
@endunless
<li class="paginate_button previous @unless($pager->previousPageUrl())disabled @endunless">
<a href="{{ $pager->previousPageUrl() }}"><i class="fa fa-angle-left"></i></a>
</li>
@while($pager->paging++ < $pager->lastPage())
@if (abs($pager->paging - $pager->currentPage()) >= 2)
{{-- Generate relative links (eg. +10,etc) --}}
@if(in_array(abs($pager->paging - $pager->currentPage()), array(10, 50, 100, 500, 1000))
and $pager->paging != 1 and $pager->paging != $pager->lastPage())
<li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
<a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
<!-- + {{ $pager->paging - $pager->currentPage() }} -->{{ $pager->paging }}
</a>
</li>
@endif
@else
<li class="paginate_button @unless($pager->currentPage() != $pager->paging)active @endunless">
<a title="Results from {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['start'] }} to {{ PaginationStartEnd($pager->paging, $pager->perPage(), $pager->total())['end'] }} of {{ $pager->total() }}" href="{{ $pager->url($pager->paging) }}">
{{ $pager->paging }}
</a>
</li>
@endif
@endwhile
<li class="paginate_button next @unless($pager->nextPageUrl())disabled @endunless">
<a href="{{ $pager->nextPageUrl() }}"><i class="fa fa-angle-right"></i></a>
</li>
@unless($pager->lastPage() - $pager->currentPage() < 2)
<li class="paginate_button next">
<a href="{{ $pager->url($pager->lastPage()) }}" title="Last Page"><i class="fa fa-angle-double-right"></i></a>
</li>
@endunless
</ul>
@endif
分頁開始結束函數
if (!function_exists('PaginationStartEnd')) {
function PaginationStartEnd($currentPage, $perPage, $total)
{
$pageStart = number_format( $perPage * ($currentPage - 1));
$pageEnd = $pageStart + $perPage;
if ($pageEnd > $total)
$pageEnd = $total;
$pageStart++;
return array('start' => number_format($pageStart), 'end' => number_format($pageEnd));
}
}
您可以根據需要更多地使用和自定義它。
注意: $pager->paging 是在控制器動作中聲明的變量設置為 0
在 Laravel 5.4 中
我找到的最簡單的方法,通過使用vendor:publish
命令將它們導出到您的resources/views/vendor
目錄
php artisan vendor:publish --tag=laravel-pagination
然后轉到resources\\views\\vendor\\pagination\\default.blade.php
並在那里進行定制。
可以在此處找到有關此的完整文檔
我將此代碼與 k7 主題一起使用,並將此代碼與它們的內置類一起使用。 您還可以根據需要將此代碼與您的主題和課程一起使用。
嘗試這樣做。
<section class="page-paging pt-0">
<div class="container">
<div class="row">
<div class="col-12">
<nav aria-label="Page navigation example">
@if ($view_post->lastPage() > 1)
<ul class="pager list-inline mb-0 text-center">
<li class="{{ ($view_post->currentPage() == 1) ? ' disabled' : '' }}p-1 list-inline-item float-sm-left">
<a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url(1) }}">
<i class="fa fa-angle-left pr-1"></i> Prev
</a>
</li>
@for ($i = 1; $i <= $view_post->lastPage(); $i++)
<li class=" p-1 list-inline-item d-none d-md-inline-block">
<a class="{{ ($view_post->currentPage() == $i) ? ' active' : '' }} page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($i) }}">{{ $i }}
</a>
</li>
@endfor
<li class="{{ ($view_post->currentPage() == $view_post->lastPage()) ? ' disabled' : '' }} p-1 list-inline-item float-sm-right">
<a class="active page-link brd-gray px-4 py-3 font-weight-bold" href="{{ $view_post->url($view_post->currentPage()+1) }}"> Next
<i class="fa fa-angle-right pl-1"></i>
</a>
</li>
</ul>
@endif
</nav>
</div>
</div>
</div>
</section>
這是一個簡單的定制 Laravel 分頁解決方案,包括服務器端和客戶端代碼。
假設使用 Laravel 5.2 和以下包含的視圖:
@include('pagination.default', ['pager' => $data])
特征
default.blade.php
@if ($paginator->last_page > 1)
<ul class="pagination pg-blue">
<li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
<a class="page-link" tabindex="-1" href="{{ '/locate-vendor/'}}{{ substr($paginator->prev_page_url,7) }}">
Previous
</a>
</li>
<li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
<a class="page-link" tabindex="-1" href="{{ '/locate-vendor/1'}}">
First
</a>
</li>
@if ( $paginator->current_page > 5 )
<li class="page-item">
<a class="page-link" tabindex="-1">...</a>
</li>
@endif
@for ($i = 1; $i <= $paginator->last_page; $i++)
@if ( ($i > ($paginator->current_page - 5)) && ($i < ($paginator->current_page + 5)) )
<li class="page-item {{($paginator->current_page == $i)?'active':''}}">
<a class="page-link" href="{{'/locate-vendor/'}}{{$i}}">{{$i}}</a>
</li>
@endif
@endfor
@if ( $paginator->current_page < ($paginator->last_page - 4) )
<li class="page-item">
<a class="page-link" tabindex="-1">...</a>
</li>
@endif
<li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
<a class="page-link" href="{{'/locate-vendor/'}}{{$paginator->last_page}}">
Last
</a>
</li>
<li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
<a class="page-link" href="{{'/locate-vendor/'}}{{substr($paginator->next_page_url,7)}}">
Next
</a>
</li>
</ul>
@endif
服務器端控制器功能
public function getVendors (Request $request)
{
$inputs = $request->except('token');
$perPage = (isset($inputs['per_page']) && $inputs['per_page']>0)?$inputs['per_page']:$this->perPage;
$currentPage = (isset($inputs['page']) && $inputs['page']>0)?$inputs['page']:$this->page;
$slice_init = ($currentPage == 1)?0:(($currentPage*$perPage)-$perPage);
$totalVendors = DB::table('client_broker')
->whereIn('client_broker_type_id', [1, 2])
->where('status_id', '1')
->whereNotNull('client_broker_company_name')
->whereNotNull('client_broker_email')
->select('client_broker_id', 'client_broker_company_name','client_broker_email')
->distinct()
->count();
$vendors = DB::table('client_broker')
->whereIn('client_broker_type_id', [1, 2])
->where('status_id', '1')
->whereNotNull('client_broker_company_name')
->whereNotNull('client_broker_email')
->select('client_broker_id', 'client_broker_company_name','client_broker_email')
->distinct()
->skip($slice_init)
->take($perPage)
->get();
$vendors = new LengthAwarePaginator($vendors, $totalVendors, $perPage, $currentPage);
if ($totalVendors) {
$response = ['status' => 1, 'totalVendors' => $totalVendors, 'pageLimit'=>$perPage, 'data' => $vendors, 'Message' => 'Vendors Details Found.'];
} else {
$response = ['status' => 0, 'totalVendors' => 0, 'data' => [], 'pageLimit'=>'', 'Message' => 'Vendors Details not Found.'];
}
return response()->json($response, 200);
}
如果您想使用 next 和 prev 自定義分頁鏈接。 你可以在 Paginator.php 里面看到,有一些方法我正在使用 Laravel 7
<a href="{{ $paginator->previousPageUrl() }}" < </a>
<a href="{{ $paginator->nextPageUrl() }}" > </a>
要限制項目,在控制器中使用 paginate()
$paginator = Model::paginate(int);
感謝 MantisD 的帖子,對於 Bootstrap 4,這很好用。
<?php
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>
@if ($paginator->lastPage() > 1)
<div id="news_paginate" class="dataTables_paginate paging_simple_numbers">
<ul class="pagination">
<li id="news_previous" class="paginate_button page-item previous {{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
<a class="page-link" tabindex="0" href="{{ $paginator->url(1) }}">Previous</a>
</li>
@for ($i = 1; $i <= $paginator->lastPage(); $i++)
<?php
$half_total_links = floor($link_limit / 2);
$from = $paginator->currentPage() - $half_total_links;
$to = $paginator->currentPage() + $half_total_links;
if ($paginator->currentPage() < $half_total_links) {
$to += $half_total_links - $paginator->currentPage();
}
if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
$from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
}
?>
@if ($from < $i && $i < $to)
<li class="paginate_button page-item {{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
<a class="page-link" href="{{ $paginator->url($i) }}">{{ $i }}</a>
</li>
@endif
@endfor
<li id="news_next" class="paginate_button page-item {{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
@if($paginator->currentPage() == $paginator->lastPage())
<a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()) }}" >End</a>
@else
<a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
@endif
</li>
</ul>
</div>
@endif
如果你想改變 url 中的頁碼而不是像 /pageNo 這樣的數據。 例如:/2。 您可以使用 jquery 更改 url 。 我在帶有 url 的 get 方法中有一些數據。
$(function () {
$('.pagination li a').each(function () {
var link = $(this).attr('href');
var pageText = $(this).text();
var activePage = parseInt($('.pagination li.active span').text());
if (pageText.trim() == "«") {
pageText = activePage - 1;
} else if (pageText.trim() == "»") {
pageText = activePage + 1;
}
link = link.replace('?', '/' + pageText + '?');
link = link.replace('&page=' + pageText, '');
$(this).attr('href', link);
console.log(link);
});
})
Laravel 自定義分頁與來自其他 api 的數據寫入 Node.js
Controller
class BlogController extends Controller
{
$perPage = 20;
$page=1;
if (isset($_GET["page"]))
$page = $_GET["page"];
//Third party api to get records, you can put directly your url , I made a Api class to call third party api
$records = Api::getBlogs($page, $perPage);
$blogs = $records['data'];
$totalRecords = $records['totalRecords'];
return view('blog.all',['blogs'=>$blogs,
'pagination' =>array('totalRecords'=>$totalRecords, 'perPage'=>$perPage)
]);
}
博客視圖
@foreach($blogs as $blog)
{{$blog->title}}
@endforeach
@include('pagination.pagination', ['pagination'=>$pagination])
在視圖“pagination”中創建一個新文件夾並在其中創建一個新文件“pagination.blade.php”,放置此內容
<?php
$page=1;
if (isset($_GET["page"]))
$page = $_GET["page"];
$totalPages = ceil($pagination['totalRecords'] / $pagination['perPage']);
$count = 3;
$startPage = max(1, $page - $count);
$endPage = min( $totalPages, $page + $count);
$prev = $page - 1;
$next = $page + 1;
?>
<nav class="posts-navigation" aria-label="posts">
<ul class="pagination">
<li class="<?php if($page <= 1){ echo 'disabled'; } ?>">
<a href="<?php if($page <= 1){ echo '#'; } else { echo "?page=" . $prev; } ?>" aria-label="Previous" >
<i class="fas fa-angle-left"></i>
</a>
</li>
<?php for($i = $startPage; $i <= $endPage; $i++ ): ?>
<li class="<?php if($page == $i) {echo 'active'; } ?>"><a href="?page=<?= $i; ?>"><?= $i; ?></a></li>
<?php endfor; ?>
<li class="<?php if($page >= $totalPages) { echo 'disabled'; } ?>">
<a href="<?php if($page >= $totalPages){ echo '#'; } else {echo "?page=". $next; } ?>" aria-label="Next">
<i class="fas fa-angle-right"></i>
</a>
</li>
</ul>
</nav>
Laravel 8 自定義分頁
我是 Laravel 的新手,除了其他自定義解決方案外,我嘗試使用以下功能復制 phpadmin 樣式分頁
首先運行以下命令發布 Laravel 分頁
php 工匠供應商:發布 --tag=laravel-pagination
這將在視圖/供應商/分頁中生成文件夾而不是
只要確保你的 AppServiceProvider 中有這個。
use Illuminate\Pagination\Paginator;
public function boot()
{
Paginator::useBootstrap();
}
你對go很好。
在 default.blade.php 或 mypagination-selectable.blade.php 中使用以下代碼
<ul class="pagination pagination mb-0">
{{-- Previous Page Link --}}
@if ($paginator->onFirstPage())
<li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.first')">
<span class="page-link" aria-hidden="true">1 «</span>
</li>
<li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.previous')">
<span class="page-link" aria-hidden="true">‹</span>
</li>
@else
<li class="page-item">
<a class="page-link" href="{{ $paginator->Url(1) }}" rel="first"
aria-label="@lang('pagination.previous')">1 «</a>
</li>
<li class="page-item">
<a class="page-link" href="{{ $paginator->previousPageUrl() }} " rel="prev"
aria-label="@lang('pagination.previous')">‹</a>
</li>
@endif
{{-- Link of Pages with dropdown including Previous and Next --}}
{{-- This easily fit in 3-columns --}}
<div class="d-flex justify-content-center mx-1 " style="font-size:small;">
<form action="#" method="get" class="d-flex input-group-sm ">
@csrf
<select name={{ $paginator->getPageName() }} id={{ $paginator->getPageName() }} onchange="return pagesubmit($(this).val())">
@foreach (range(1, $paginator->lastPage()) as $i)
<option value={{ $paginator->url($i) }} @if($paginator->currentPage() == $i) selected @endif >{{ $i }} </option>
@endforeach
</select>
</form>
</div>
{{-- Next Page Link --}}
@if ($paginator->hasMorePages())
<li class="page-item">
<a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next"
aria-label="@lang('pagination.next')">›</a>
</li>
<li class="page-item">
<a class="page-link" href="{{ $paginator->Url($paginator->lastPage()) }}" rel="last"
aria-label="@lang('pagination.next')">» {{ $paginator->lastPage() }}</a>
</li>
@else
<li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.next')">
<span class="page-link" aria-hidden="true">›</span>
</li>
<li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.last')">
<a class="page-link" href="{{ $paginator->Url($paginator->lastPage()) }}" rel="last"
aria-label="@lang('pagination.next')">» {{ $paginator->lastPage() }}</a>
</li>
@endif
</ul>
在你的 controller
public function index(Request $request)
{
$units_perpage = 10;//Per_Page setting
$current_pageno = request()->input('units_pageno',1);// setting Current page based on input
$sysunits = DB::table('sys_units')
->orderBY('unit_title')
->latest()
->paginate($perPage = $units_perpage, $columns = ['*'], $pageName = 'units_pageno');
}
...
return view('appunits_index',compact('sysunits'))
->with('i',($current_pageno - 1) * $units_perpage);
}
在你的刀片中
{{--Application Pagination --}}
<div class="col-3 d-flex justify-content-end">
{!! $sysunits->appends(['sort' => 'unit_title'])
->links('pagination::mypagination-selectable') !!}
</div>
用腳本作為
<script>
//Called from Custom Pagination select blade
function pagesubmit($page_url) {
window.location = $page_url;
}
</script>
這是另一個例子
控制器
$projects = $projects->offset($page * $limit)->paginate($limit);
刀片文件
{{$projects->links('provider.pages.merchandising.partials.paginator')}}
分頁器視圖
<div class="d-flex flex-wrap mr-3"> <:-- first/previous --> @if($paginator->currentPage() > 1) <a href="{{ $paginator->url(1) }}" class="btn btn-icon btn-sm btn-light-primary mr-2 my-1"> <i class="ki ki-bold-double-arrow-back icon-xs"></i> </a> <a href="{{$paginator->url($paginator->currentPage() - 1)}}" class="btn btn-icon btn-sm btn-light-primary mr-2 my-1"> <i class="ki ki-bold-arrow-back icon-xs"></i> </a> @else <a href="javascript:void(0)" class="btn btn-icon btn-sm btn-light-secondary mr-2 my-1"> <i class="ki ki-bold-double-arrow-back icon-xs text-white"></i> </a> <a href="javascript?void(0)" class="btn btn-icon btn-sm btn-light-secondary mr-2 my-1"> <i class="ki ki-bold-arrow-back icon-xs text-white"></i> </a> @endif @php $interval = isset($interval): abs(intval($interval)); 3; $from = $paginator->currentPage() - $interval; if($from < 1){ $from = 1; } $to = $paginator->currentPage() + $interval; if($to > $paginator->lastPage()){ $to = $paginator->lastPage(). } @endphp @if($from > 1) <a href="{{ $paginator->url($from - 1) }}" class="btn btn-icon btn-sm border-0 btn-hover-primary mr-2 my-1">..;</a> @endif @for($i = $from; $i <= $to; $i++) @php $isCurrentPage = $paginator->currentPage() == $i? @endphp <a href="{{:$isCurrentPage: $paginator->url($i)? 'javascript:void(0)' }}" class="{{ $isCurrentPage. 'active'. '' }} btn btn-icon btn-sm border-0 btn-hover-primary mr-2 my-1"> {{ $i }} </a> @endfor @if($to < $paginator->lastPage()) <a href="{{ $paginator->url($to + 1) }}" class="btn btn-icon btn-sm border-0 btn-hover-primary mr-2 my-1">.::</a> @endif @if($paginator->currentPage() < $paginator->lastPage()) <a href="{{ $paginator->url($paginator->currentPage() + 1) }}" class="btn btn-icon btn-sm btn-light-primary mr-2 my-1"> <i class="ki ki-bold-arrow-next icon-xs"></i> </a> <a href="{{ $paginator->url($paginator->lastpage()) }}" class="btn btn-icon btn-sm btn-light-primary mr-2 my-1"> <i class="ki ki-bold-double-arrow-next icon-xs"></i> </a> @else <a href="javascript void(0)" class="btn btn-icon btn-sm btn-light-primary mr-2 my-1"> <i class="ki ki-bold-arrow-next icon-xs"></i> </a> <a href="javascript void(0)" class="btn btn-icon btn-sm btn-light-primary mr-2 my-1"> <i class="ki ki-bold-double-arrow-next icon-xs"></i> </a> @endif </div>
它應該看起來像這樣。
public function paginate($items, $perPage, $page = null){ $page = $page?: (Paginator::resolveCurrentPage()?: 1); $總計 = 計數($items); $currentpage = $page; $offset = ($currentpage * $perPage) - $perPage; $itemstoshow = array_slice($items, $offset, $perPage); 返回新的 LengthAwarePaginator($itemstoshow,$total,$perPage); }
2.在class controller參數之前使用:
使用 Illuminate\Pagination\Paginator; 使用 Illuminate\Pagination\LengthAwarePaginator;
$variable = $this->paginate( your_array_data(), Per_page_data_show _amount( like 30)); $變量 >withPath('');
{{ $helloZai_bank_withdraw->links() }}
5.使用Boot方法分頁設計app/Providers/AppServiceProvider.php文件
使用 Illuminate\Pagination\Paginator;
6.在boot function app/Providers/AppServiceProvider.php文件中粘貼代碼:
分頁器::useBootstrap();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.