渲染前检查模板是否存在 [英] Check if template exists before rendering

查看:32
本文介绍了渲染前检查模板是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在调用渲染之前检查树枝模板是否存在?try catch 块似乎不起作用,至少在开发环境中是这样,而且,我更喜欢检查而不是异常的成本.

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.

这个类TwigEngine有一个exists()方法,但是没有找到使用示例.

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

另一种方法是捕获 render() 方法抛出的异常,如下所示:

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.
  }

在普通控制器中...

$this->render('...')

只是...的别名

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

...而...

$this->get('...') 

... 是

$this->container->get('...')

看看Symfony\FrameworkBundle\Controller\Controller.

这篇关于渲染前检查模板是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆