7
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.

4

5 回答 5

11

我认为没有直接的方法来检查路线是否存在。但是您可以通过路由器服务查找路由是否存在。

$router = $this->container->get('router');

然后,您可以获得一个路由集合并调用get()给定的路由,如果它不存在则返回 null。

$router->getRouteCollection()->get('_'. $specific. '_thanks');
于 2013-01-03T10:01:13.150 回答
9

getRouteCollection()在运行时使用不是正确的解决方案。执行此方法将需要重建缓存。这意味着路由缓存将在每个请求上重建,使您的应用程序比需要的慢得多。

如果要检查路由是否存在,请使用 try ... catch 构造:

use Symfony\Component\Routing\Exception\RouteNotFoundException;

try {
    dump($router->generate('some_route'));
} catch (RouteNotFoundException $e) {
    dump('Oh noes, route "some_route" doesn't exists!');
}
于 2016-07-02T14:41:29.480 回答
1

尝试这样的事情,检查路线是否存在于所有路线的数组中:

    $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'));
    }
于 2013-01-03T10:03:19.033 回答
0

你检查你的演员了吗?你确定路线吗?通常路线以

'WEBSITENAME_'.$specific.'_thanks'

于 2013-01-03T10:09:44.423 回答
-4

尝试这个:

if ($u == $this->generateUrl('_'.$specific.'_thanks') )
于 2013-01-03T09:57:25.627 回答