简体   繁体   中英

Check routing in symfony2

I want to learn symfony and I start to create a small application. I have a question related to the routes. So, I have in my project the routes :

/admin/homepage , /admin/news , admin/galery

No if I write in url /admin , this route doesn't exist and I get as error No route found for "GET /admin/" . Exist a way to check if route doesn't exist and redirect to another route for example ? Thx in advance and sorry for my english My routes :

news_all:
path: /news/all/{page}
defaults: { _controller: AppAdminBundle:News:all, page: 1 }
requirements:
    page: \d+
    _method:  GET|POST
news_add:
path: /news/add
defaults: { _controller: AppAdminBundle:News:add }

In your case the best solution would be to override default ExceptionController and add custom logic there, eg redirection to other page - according to the docs: http://symfony.com/doc/current/cookbook/controller/error_pages.html#overriding-the-default-exceptioncontroller

# app/config/config.yml
twig:
    exception_controller:  AppBundle:Exception:showException

Note: Instead of creating a new exception controller from scratch you can, of course, also extend the default ExceptionController . In that case, you might want to override one or both of the showAction() and findTemplate() methods. The latter one locates the template to be used.

Symfony's good practise are to set rout in your controller, using annotations

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

and

/**
* @Route("/news/add", name="news_add")
*/
public function addAction()
{
    // ...
}

Also, with annotation, you can set rout for a whole controller. Which is, in your case, what you're looking for.

/**
* @Route("/admin")
*/
class NewsController extends Controller
{
    /**
     * @Route("/news/add", name="news_add")
     */
    public function addAction()
    {
        // ...
    }
}

Also, I advice you to take a look at @Template annotation .

Else, to answer your question, I think you can make a custom twig function (check this link for more information). Function that checks is the given name a valid route:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM