Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if route exists in Twig Template (Symfony 2)

I want to generate a Navigation from my Database where I store the names of my routes as link targets. My Controller simply gets all necessary navigation entries from the database and returns the rows which are used directly in my twig template.

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

Thus there is the possibility that a route does not exist which results in Error 500.

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

AFAIK my Controller could catch Twig Exceptions but I just want twig to ignore navigation entries which are not valid. Any idea?

like image 444
csc Avatar asked Jun 21 '13 17:06

csc


1 Answers

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

But I'm not sure it's a good idea to handle navigation in such way (in database). Maybe you'd better use something else?

like image 166
Hast Avatar answered Nov 15 '22 15:11

Hast