问题
if ($u = $this->generateUrl('_'.$specific.'_thanks'))
return $this->redirect($u);
else
return $this->redirect($this->generateUrl('_thanks'));
I wan't to redirect to the _specific_thanks
url when it exist. So How to check if a url exist?
When I did that, I had this error:
Route "_specific_thanks" does not exist.
回答1:
I don't think there's a direct way to check if a route exists. But you can look for route existence through the router service.
$router = $this->container->get('router');
You can then get a route collection and call get()
for a given route, which returns null if it doesn't exist.
$router->getRouteCollection()->get('_'. $specific. '_thanks');
回答2:
Using getRouteCollection()
on runtime is not the correct solution. Executing this method will require the cache to be rebuilt. This means that routing cache will be rebuilt on each request, making your app much slower than needed.
If you want to check whether a route exists or not, use the try ... catch construct:
use Symfony\Component\Routing\Exception\RouteNotFoundException;
try {
dump($router->generate('some_route'));
} catch (RouteNotFoundException $e) {
dump('Oh noes, route "some_route" doesn't exists!');
}
回答3:
Try something like this, check the route exists in the array of all routes:
$router = $this->get('router');
if (array_key_exists('_'.$specific.'_thanks',$router->getRouteCollection->all())){
return $this->redirect($this->generateUrl('_'.$specific.'_thanks'))
} else {
return $this->redirect($this->generateUrl('_thanks'));
}
回答4:
Did you check your cast? And are you sure about the route? usually route start with
'WEBSITENAME_'.$specific.'_thanks'
回答5:
Try this:
if ($u == $this->generateUrl('_'.$specific.'_thanks') )
来源:https://stackoverflow.com/questions/14136484/check-url-before-redirect-symfony2