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

  1. <?php
  2. namespace App\Presenters;
  3. use Illuminate\Support\HtmlString;
  4. use Illuminate\Pagination\BootstrapThreePresenter;
  5. class PagiationPresenter extends BootstrapThreePresenter
  6. {
  7. public function render()
  8. {
  9. if ($this->hasPages()) {
  10. return new HtmlString(sprintf(
  11. '<ul class="pagination pagination-sm no-margin">%s %s %s</ul>',
  12. $this->getPreviousButton(),
  13. $this->getLinks(),
  14. $this->getNextButton()
  15. ));
  16. }
  17. return '';
  18. }
  19. }

创建服务提供者PaginationServiceProvider

  1. <?php
  2. namespace App\Providers;
  3. use App\Presenters\PagiationPresenter;
  4. use Illuminate\Pagination\Paginator;
  5. use Illuminate\Pagination\AbstractPaginator;
  6. use Illuminate\Support\ServiceProvider;
  7. class PaginationServiceProvider extends ServiceProvider
  8. {
  9. /**
  10. * Bootstrap the application services.
  11. *
  12. * @return void
  13. */
  14. public function boot()
  15. {
  16. //自定义分页
  17. Paginator::presenter(function (AbstractPaginator $paginator) {
  18. return new PagiationPresenter($paginator);
  19. });
  20. }
  21. /**
  22. * Register the application services.
  23. *
  24. * @return void
  25. */
  26. public function register()
  27. {
  28. //
  29. }
  30. }

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

  1. 'providers' => [
  2. /*
  3. * Laravel Framework Service Providers...
  4. */
  5. ...
  6. App\Providers\PaginationServiceProvider::class,
  7. ],

实例源码

我的开源博客Moell Blog