首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用KnpPaginator创建分页

使用KnpPaginator创建分页
EN

Stack Overflow用户
提问于 2015-03-27 17:17:48
回答 1查看 380关注 0票数 0

我尝试使用捆绑包KnpPaginator在我的网站上创建一个分页。在我的存储库中,我创建了一个查询:

代码语言:javascript
复制
public function getProductsOrderByDateDesc($id_category = null, $max = null){
    $qb = $this->createQueryBuilder('p')
        ->orderBy('p.created_at', 'DESC');

    if($max) {
        $qb->setMaxResults($max);
    }
    if($id_category) {
        if(is_array($id_category)){
            $aIdCategory = implode("','",$id_category);
            $qb->andWhere('p.category IN (:ids)')
                ->setParameter('ids', $aIdCategory);
        }else{
            $qb->andWhere('p.category = :category_id')
                ->setParameter('category_id', $id_category);
        }
    }
    $query = $qb->getQuery();
    return $query->getArrayResult();
}

在我的控制器中,我这样做:

代码语言:javascript
复制
    $repositoryProduct = $em->getRepository('ShopDesktopBundle:Product');
    $aProducts          = array();
    $aProducts          = $repositoryProduct->getProductsOrderByDateDesc($id);
    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $aProducts,
        $this->get('request')->query->get('page', 1),
        3
    );
    return $this->render('ShopDesktopBundle:Category:category.html.twig',array(
        'aProducts'         => $aProducts,
        'pagination'        => $pagination
    ));

在视图中,我仅显示此分页:

代码语言:javascript
复制
<div class="navigation">
     {{ knp_pagination_render(pagination) }}
</div>

提前进行Thx

EN

回答 1

Stack Overflow用户

发布于 2015-03-27 17:25:14

几乎正确,但是你必须使用分页对象而不是'aProducts‘。在您的视图中,使用以下代码:

代码语言:javascript
复制
{% for product in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
    <td>{{ product.id }}</td>
    <td>{{ product.title }}</td>
</tr>
{% endfor %}

查看文档中“查看”下的更多信息:https://github.com/KnpLabs/KnpPaginatorBundle

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29297045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档