这是我的分页代码:
Controller :
public function index($request, $response) {
$current_page = $request->getParam('page');
Paginator::currentPageResolver(function() use ($current_page) {
return $current_page;
});
$routes = $this->route->paginate(2);
return $this->view->render($response, 'dashboard/dashboard.twig', [
'routes' => $routes
]);
}
查看:
{% for route in routes %}
{{ route.route_name }}<br>
{% endfor %}
当我运行浏览器时没有问题。当我在 url 中添加 page
参数时,它也有效。
但是当我尝试在分页对象中添加 links
方法时。
{% for route in routes %}
{{ route.route_name }}<br>
{% endfor %}
{{ routes.links() }} {# <--- This one #}
提示错误
Message: Call to a member function make() on null
File: C:\xampp\htdocs...\vendor\illuminate\pagination\LengthAwarePaginator.php
更新:
当我尝试回显 Controller 内的 links()
方法时。我发现了这个错误。
$routes = $this->route->paginate(5);
echo $routes->links();
die();
Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in C:\xampp\htdocs...\vendor\illuminate\pagination\AbstractPaginator.php on line 377
然后我查看了源码,是这个
/**
* Get an instance of the view factory from the resolver.
*
* @return \Illuminate\Contracts\View\Factory
*/
public static function viewFactory()
{
return call_user_func(static::$viewFactoryResolver);
}
有什么解决办法吗?
这个方法在5.2有效,引用这个链接。
Pagination with Twig and Eloquent-5.2
但不幸的是,它不再起作用了。
最佳答案
在 PHP 7 中,您可以创建匿名类以在 viewVactory 中注册它:
$view = $this->container->get('view');
$view->getEnvironment()->addTest(new Twig_SimpleTest('string', function($value) {
return is_string($value);
}));
\Illuminate\Pagination\Paginator::viewFactoryResolver(function() use ($view) {
return new class($view) {
private $view;
private $template;
private $data;
public function __construct(\Slim\Views\Twig $view)
{
$this->view = $view;
}
public function make(string $template, $data = null)
{
$this->template = $template;
$this->data = $data;
return $this;
}
public function render()
{
return $this->view->fetch($this->template, $this->data);
}
};
});
\Illuminate\Pagination\Paginator::currentPageResolver(function() use ($request) {
return $request->getParam('page');
});
return $view->render($response, 'list.twig', [
'items' => Material::paginate(10),
]);
在 list.twig
中:
{{ items.render('pagination.twig') | raw }}
在 pagination.twig
中:
{% if paginator.hasPages() %}
<ul class="pagination">
{% for element in elements %}
{% if element is string %}
<li class="disabled"><span>{{ element }}</span></li>
{% endif %}
{% if element is iterable %}
{% for page, url in element %}
{% if page == paginator.currentPage() %}
<li class="active"><span>{{ page }}</span></li>
{% else %}
<li><a href="{{ url }}">{{ page }}</a></li>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
</ul>
{% endif %}
关于php - 使用 Slim 3 使用 Eloquent-5.3 进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40395805/