Check if template exists before rendering
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 {
$this->get('templating')->render('AcmeDemoBundle:Foo:bar.html.twig')
} catch (\Exception $ex) {
// your conditional code here.
}
In a normal controller ...
$this->render('...')
is only an alias for ...
$this->container->get('templating')->renderResponse($view, $parameters, $response);
... while ...
$this->get('...')
... is an alias for
$this->container->get('...')
Have a look at Symfony\FrameworkBundle\Controller\Controller.
The templating
service will be removed in future Symfony versions. The future-proof solution based on the twig
service is:
if ($this->get('twig')->getLoader()->exists('AcmeDemoBundle:Foo:bar.html.twig')) {
// ...
}