Laravel 通过服务提供者来自定义分页样式

2016-09-18 13:53:39   php

  laravel  

需求介绍

laravel默认了分页,实现非常优雅,但有时候会遇到修改默认的样式,比如我要将默认的<ul class="pagination">修改为<ul class="pagination pagination-sm no-margin">

解决办法切入点

Laravel自带的分页链接样式由Illuminate\Pagination\BootstrapThreePresenter的render方法生成,我们在此方法上做文章即可实现。

创建重写render方法的类

创建文件:App/Presenters/PagiationPresenter

<?php

namespace App\Presenters;

use Illuminate\Support\HtmlString;
use Illuminate\Pagination\BootstrapThreePresenter;

class PagiationPresenter extends BootstrapThreePresenter
{
    public function render()
    {
        if ($this->hasPages()) {
            return new HtmlString(sprintf(
                '<ul class="pagination pagination-sm no-margin">%s %s %s</ul>',
                $this->getPreviousButton(),
                $this->getLinks(),
                $this->getNextButton()
            ));
        }

        return '';
    }
}

创建服务提供者PaginationServiceProvider

<?php

namespace App\Providers;

use App\Presenters\PagiationPresenter;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\AbstractPaginator;
use Illuminate\Support\ServiceProvider;

class PaginationServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //自定义分页
        Paginator::presenter(function (AbstractPaginator $paginator) {
            return new PagiationPresenter($paginator);
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

将服务提供者添加到config/app.php

'providers' => [

        /*
         * Laravel Framework Service Providers...
         */
         ...
        App\Providers\PaginationServiceProvider::class,
    ],

实例源码

我的开源博客Moell Blog