2016-02-29 38 views
1

我有一個問題:對於這樣的例子,我有一個symfony3應用程序,它有以下途徑:/admin/loginadmin/newsadmin/gallery,但路線/admin/authentification不存在。所以這個想法是,如果路線不存在,我想將用戶重定向到主頁/。你能幫我嗎 ?在此先感謝和抱歉,我的英語重定向如果路線does'n存在

+2

可能重複[重定向所有事件監聽器「找不到路由404未找到 - NotFoundHttpException」](http://stackoverflow.com/questions/26464624/redirect-with-event-listener-for-all-no -route-發現-404未找到-notfoundhtt) – chalasr

回答

0

我不相信這是最好的解決,但你可以使用一個UrlMatcher來檢查URL你傳遞關聯到一個可用的路線:

/** 
* @Route("/debug") 
*/ 

public function DebugAction(){ 
    $router = $this->get('router'); 

    //Get all the routes that exist. 
    $routes = $router->getRouteCollection(); 
    $context = $router->getContext(); 

    $urlMatcher = new UrlMatcher($routes, $context); 

    $url = '/admin/login'; 
    try{ 
     //UrlMatcher::match() will throw a ResourceNotFoundException if the route 
     //doesn't exist. 
     $urlMatcher->match($url); 
     return $this->redirect($url); 
    } catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e){ 
     return $this->redirect('/'); 
    } 
} 

我對這個解決方案並不特別熱衷,因爲它依賴於捕獲異常,而不是檢查布爾值來確定路由是否存在。

0

您可以檢查路由是否存在。

function routeExists($name) 
{ 
    // I assume that you have a link to the container in your twig extension class 
    $router = $this->container->get('router'); 
    return (null === $router->getRouteCollection()->get($name)) ? false : true; 
} 

並根據結果,做重定向到路由或默認網頁,或任何你需要的。