K. Weber K. Weber - 5 months ago 272
Twig Question

Check if template exists before rendering

is there a way to check if twig template exists before calling to render? A try catch block seems not to work, at least in dev environment, and plus, I prefer a check than the cost of an exception.

This class TwigEngine has an exists() method, but didn't find examples on use.


The service holding the twig engine if configured as default is 'templating'.

Inside your Controller do the following:

if ( $this->get('templating')->exists('AcmeDemoBundle:Foo:bar.html.twig') ) {
     // ...

The alternative would be catching exception the render() method throws like this:

 try {
  } catch (\Exception $ex) {
     // your conditional code here.

In a normal controller ...


is only an alias for ...

$this->container->get('templating')->renderResponse($view, $parameters, $response);

... while ...


... is an alias for


Have a look at Symfony\FrameworkBundle\Controller\Controller.