生成slug时出现错误Twig,缺少参数(" slug")以生成URL

时间:2018-04-26 12:59:39

标签: symfony twig

我想渲染我的Twig产品页面及其url-slug。我的控制器:

* @Route("/item/{id}", name="app_showitem_getid", requirements={"id": "\d+"})
* @param int $id
* @return Response
* @throws \Doctrine\ORM\NonUniqueResultException
public function getid(int $id):Response

{
    $repository = $this->getDoctrine()->getRepository(Item::class);
    $item = $repository->findBy($id);

    return $this->render("item/prodpage.html.twig", ["items"=>$item]);
}

* @Route("/item/{slug}", name="app_showslug_getslug")
* @return Response
* @throws \Doctrine\ORM\NonUniqueResultException
public function getslug(string $slug)

{
    $em = $this->getDoctrine()->getManager();

    $repository = $em->getRepository(Item::class);

    $itemSlug = $repository->findBy(["slug"=>$slug]);

    $this->generateUrl('app_showslug_getslug', [array("slug"=> array($itemSlug))],UrlGeneratorInterface::ABSOLUTE_URL);
}

档案routes.yaml:

app_item_getid:
    path:/item/{id}
    controller: App\Controller\ShowitemController::getid
    requirements:
        id:'\d+'

我的template.html.twig doc:

{% for item in items%}
    -->This link target the product-page:
      "{{ path('app_showitem_getid', {'id': item.id}) }}"
{% endfor%}

如何生成一个template.twig,它通过id及其slug定位到item的产品页面? 我无法正确渲染产品页面,因为它会丢失"参数丢失"错误,但它的slug在那里,在url! 缺少什么?

2 个答案:

答案 0 :(得分:0)

我想在这里:

public function getid(int $id):Response
{
    ***********************************
    $item = $repository->find($id);
    ***********************************
}

答案 1 :(得分:0)

If getid($id) is the controller action it appears to be from the @Route comment above it, you can have the framework automatically fetch the item entity from the database, if it was unique.

public function getIdAction(Item $id)
{
    var_dump($id);  // $id instanceof Item::class
    // with $id->getId() or $id->id (if public), etc.
}

If id or $slug was unique, you can also -findOneBy(...) to get a single item back, instead of an array with just 1 item.