如何与KnpPaginatorBundle一起使用友好URL
我在Symfony 2.1项目中安装了KnpPaginatorBundle,还配置了Paginator 通过分页,我的URL看起来像:如何与KnpPaginatorBundle一起使用友好URL,url,symfony,pagination,Url,Symfony,Pagination,我在Symfony 2.1项目中安装了KnpPaginatorBundle,还配置了Paginator 通过分页,我的URL看起来像: http://dev.localhost/app_dev.php/news/development?page=3 是否可以将URL更改为类似这样的内容(或类似内容-不带?和=字符) 在控制器中,您需要更改以下内容: /** * @Route("/list/", name="_user_list") * @Template() */ public func
http://dev.localhost/app_dev.php/news/development?page=3
是否可以将URL更改为类似这样的内容(或类似内容-不带?和=字符)
在控制器中,您需要更改以下内容:
/**
* @Route("/list/", name="_user_list")
* @Template()
*/
public function listAction()
{
$em = $this->get('doctrine.orm.entity_manager');
$dql = "SELECT a FROM HPPTarjetaBundle:User a";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$this->get('request')->query->get('page', 1)/*page number*/,
10/*limit per page*/
);
return compact('pagination');
}
。。。为此(请参见“页面”参数):
我找到了解决方案,要解决您的问题,请遵循以下步骤: 1) 创建新路由或更改旧路由,因此在routing.yml中添加以下内容:
news_development_route:
pattern: /news/development/{page}
defaults: {_controller: AcmeMainBundle:Article:list, page: 1 }
2) 在类控制器中,按如下方式更改方法:
// Acme\MainBundle\Controller\ArticleController.php
public function listAction($page)/*add the $page param*/
{
$em = $this->get('doctrine.orm.entity_manager');
$dql = "SELECT a FROM AcmeMainBundle:Article a";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$this->get('request')->query->get('page', $page)/*change the number 1 by the $page parameter*/,
10/*limit per page*/
);
$pagination->setUsedRoute('news_development_route'); /*define the pagination route*/
// parameters to template
return $this->render('AcmeMainBundle:Article:list.html.twig', array('pagination' => $pagination));
}
就是这样我遇到了一个问题,因为参数没有默认值,但是添加默认值={“page”=1}解决了这个问题如果您在@DrMartin solution中休息,那么您必须指定查询字符串。我是这样解决的。“~”非常有用。请参阅《细枝官方手册》:, 第章:模板设计器/表达式的细枝。祝你好运,两年后。谢谢我已经测试过了,效果很好。如果您在路由中使用变量(例如
@route(“/list/{name}”,name=“\u article\u list”)
,您可以使用$pagination->addParam('name',Finance');
添加它们。我仍在搜索如何从一个干净的URL开始(因此取消设置所有当前查询字符串参数)。
news_development_route:
pattern: /news/development/{page}
defaults: {_controller: AcmeMainBundle:Article:list, page: 1 }
// Acme\MainBundle\Controller\ArticleController.php
public function listAction($page)/*add the $page param*/
{
$em = $this->get('doctrine.orm.entity_manager');
$dql = "SELECT a FROM AcmeMainBundle:Article a";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$this->get('request')->query->get('page', $page)/*change the number 1 by the $page parameter*/,
10/*limit per page*/
);
$pagination->setUsedRoute('news_development_route'); /*define the pagination route*/
// parameters to template
return $this->render('AcmeMainBundle:Article:list.html.twig', array('pagination' => $pagination));
}