限制 Laravel 分页显示的链接数量

2022-01-04 00:00:00 php laravel pagination

有什么简单的方法可以限制 Laravel 分页显示的链接数量?

Any easy way to limit how many links are shown with Laravels pagination?

目前最多显示 13 个链接(上一页,1 2 3 4 5 7 8 .. 78 79 下一页)

Currently it shows 13 links at most (Prev, 1 2 3 4 5 7 8 .. 78 79 next)

然而,这对于移动设备来说太多了,变成了两行导航......有没有办法将链接设置为例如只显示 10 个?

This however is too much for mobile devices and becomes a two line navigation... is there any way to set the links to e.g. only show 10?

我搞乱了分页演示者,但实际上似乎没有任何效果.

I have messed around with the pagination presenter but nothing actually seemed to work.

谢谢

推荐答案

定义自定义演示者的旧方法不适用于 Laravel 5.3+,显示的链接数量似乎是在 中硬编码的Illuminate/Pagination/UrlWindow::make() 的 $onEachSide 参数:

The old way of defining a custom presenter doesn't work with Laravel 5.3+, the number of links shown seems to be hard-coded in the $onEachSide parameter of Illuminate/Pagination/UrlWindow::make():

public static function make(PaginatorContract $paginator, $onEachSide = 3)

我最终只是编写了自己的 render() 函数,从 LengthAwarePaginator

I ended up just writing my own render() function, stealing some code from LengthAwarePaginator

/**
     * Stole come code from LengthAwarePaginator::render() and ::elements() to allow for a smaller UrlWindow
     *
     * @param LengthAwarePaginator $paginator
     * @param int $onEachSide
     * @return string
     */
    public static function render(LengthAwarePaginator $paginator, $onEachSide = 2)
    {
        $window = UrlWindow::make($paginator, $onEachSide);

        $elements = array_filter([
            $window['first'],
            is_array($window['slider']) ? '...' : null,
            $window['slider'],
            is_array($window['last']) ? '...' : null,
            $window['last'],
        ]);

        return LengthAwarePaginator::viewFactory()->make(LengthAwarePaginator::$defaultView, [
            'paginator' => $paginator,
            'elements' => $elements,
        ])->render();
    }
}

我们使用 Twig,所以我将其注册为 Twig 过滤器,我想可以为 Blade 做类似的事情.

We use Twig, so I registered this as a Twig filter, I imagine something similar could be done for Blade.

相关文章