Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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')) {
    // ...
}

In case you need to check for template existance from inside twig templates you have to use the array include methods, as described in the documentation:

{% include ['page_detailed.html', 'page.html'] %}

Maybe also an option:

{% include 'AcmeDemoBundle:Foo:bar.html.twig' ignore missing %}

The ignore missing addition tells twig to simply do nothing, when the template is not found.

You can do it this way using dependency injection:

use Symfony\Component\Templating\EngineInterface;

public function fooAction(EngineInterface $templeEngine)
{
    if ($templeEngine->exists("@App/bar/foo.html.twig")) {
        // ...
    }
    // ...
}

Tested with Symfony 3.4.

You can use dependency injection to get the Environment that stores the Twig configuration. Like this (in controller):

/**
 * @Route("/{path}")
 */
public function index($path, Twig\Environment $env)
{
    if (!$env->getLoader()->exists('pages/'.$path.'.html.twig')) {
        return $this->render('pages/404.html.twig');
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top