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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With