9

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?

1

1 Answer 1

15

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?

4
  • Thanks, now it works! That helped me a lot. Caching the navigation entries to take the load off the database will be the next step.
    – csc
    Jun 23, 2013 at 13:47
  • return null === $router->getRouteCollection()->get($name); is good enough. :)
    – HelpNeeder
    Apr 23, 2017 at 7:30
  • 5
    @HelpNeeder I'd say return null !== $router-> ... :)
    – ozahorulia
    Apr 24, 2017 at 7:56
  • According to that comment it's better to catch the exeption like @imanali example : github.com/symfony/symfony-docs/issues/6710 May 18, 2018 at 16:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.