问题在于路线@Route("/{cityId}")
的奇怪行为。当此路由高于其他路由(例如@Route("/editcity_{id}")
)时,它将覆盖模板。
查看屏幕截图:
/{cityId}
是第一个,/editcity_{id}
是最后一个。 当我尝试转到/editcity_2
路由/2
处理请求时,city.html.twig
会显示此错误:
/editcity_{id}
是第一个而/{cityId}
是第二个路线时,一切运作良好。我在这里:
CityController.php
:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\City;
use AppBundle\Form\Type\CityType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class CityController extends Controller
{
/**
* @Route("/addcity")
* @param Request $request
* @return Response
*/
public function addCityAction(Request $request) {
$city = new City();
$form = $this->createForm(CityType::class, $city);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($city);
$em->flush();
return new Response('Created city id '.$city->getId());
}
return $this->render(':appviews:addCity.html.twig', array(
'form' => $form->createView(),
));
}
/**
* @Route("/cities")
*/
public function citiesAction(){
$em = $this->getDoctrine()->getEntityManager();
$cities = $em->getRepository('AppBundle:City')->findAll();
return $this->render('appviews/citiesList.html.twig',array('cities'=>$cities));
}
/**
* @Route("/{cityId}")
*/
public function cityAction($cityId) {
$em = $this->getDoctrine()->getManager();
$city = $em->getRepository('AppBundle:City')->find($cityId);
return $this->render('appviews/city.html.twig',array(
'city' => $city));
}
/**
* @Route("/editcity_{id}")
* @return Response
*/
public function editCityAction($id, Request $request) {
$em = $this->getDoctrine()->getEntityManager();
$city = $em->getRepository('AppBundle:City')->find($id);
$form = $this->createForm(CityType::class, $city);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($city);
$em->flush();
return new Response('Created city id '.$city->getId());
}
return $this->render(':appviews:editCity.html.twig', array(
'form' => $form->createView(),
));
}
Twig模板,city.html.twig
{% extends "appviews/base.html.twig" %}
{% block title %}Cтраница города {% endblock %}
{% block body %}
{{ dump(city)}}
{{ city.link }}
{% endblock %}
答案 0 :(得分:1)
你得到的是正常行为,因为
Symfony路由器将始终选择它找到的第一个匹配路由
并且您的/{cityId}
路由相当于/*
,例如对于这些网址属实:
/123
/add-new-article
/edit-123
/article-123.html
/123-article.html
因此,您的/editcity_{id}
路由永远不会匹配,因为您的/{cityId}
路由就是这种情况。但是你可以通过增加路线要求或路线条件来避免这种情况:
/**
* @Route("/{cityId}", requirements={ "cityId": "\d+" })
*/
\d+
要求是一个正则表达式,表示{cityId}
参数的值必须是数字(即数字)。
之后,/editcity_123
之类的网址永远不会与/{cityId}
路由匹配,只会与/editcity_{id}
路由匹配。
所以不要忘记在你的路线中添加需求以获得清晰的代码并避免这样的问题,当然在你需要的时候。
<强> REF。 :强> GCR docs
希望可以提供帮助。