Check if route exists in Twig template (Symfony 2)

I want to create navigation from my database, where I store the names of my routes as destination links. My controller simply retrieves all the necessary navigation entries from the database and returns the rows that are used directly in my branch template.

/** * @Route("/") * @Template() */ public function myAction() { $em = $this->getDoctrine()->getManager(); $navi = $em->getRepository('myBundle:Navigation')->findAll(); return array("navi" => $navi); } 

Thus, it is likely that the route does not exist, resulting in a 500 error.

I need a way to check if a named route exists or not. I tried to test it with {% if path('routeName') is defined %} ... {% endif %} , but this will not work.

AFAIK my controller can catch Twig exceptions, but I just want the branch to ignore the navigation entries that are invalid. Any idea?

+8
exception path symfony twig routes
source share
2 answers

You can create a custom twig function (see the this link for more information). A function that checks if a given name is 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; } 

But I'm not sure if it is a good idea to manage navigation this way (in the database). Maybe you better use something else?

+12
source share

You can also check:

 $router = $this->container->get('router'); try { dump($router->generate('HomePage')); } catch (RouteNotFoundException $e) { dump('Oh noes, route "HomePage" does not exists!'); } 
0
source share

All Articles