我在 Symfony 2.1 项目中安装了 KnpPaginatorBundle 并配置了 Paginator。
通过分页,我的 URL 看起来像:
http://dev.localhost/app_dev.php/news/development?page=3
是否可以将 URL 更改为这样的(或类似的 - 没有?和 = 字符)?
http://dev.localhost/app_dev.php/news/development/page/3
我在 Symfony 2.1 项目中安装了 KnpPaginatorBundle 并配置了 Paginator。
通过分页,我的 URL 看起来像:
http://dev.localhost/app_dev.php/news/development?page=3
是否可以将 URL 更改为这样的(或类似的 - 没有?和 = 字符)?
http://dev.localhost/app_dev.php/news/development/page/3
我找到了解决方案,要解决您的问题,请按照下列步骤操作:
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));
}
就是这样
在你的控制器中,你需要改变这个:
/**
* @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');
}
...对此(参见“页面”参数):
/**
* @Route("/list/{page}", name="_user_list")
* @Template()
*/
public function listAction($page)
{
$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,
$page/*page number*/,
10/*limit per page*/
);
return compact('pagination');
}