K. *_*ber 36 symfony twig transclusion
有没有办法在调用渲染之前检查twig模板是否存在?try catch块似乎不起作用,至少在开发环境中,而且,我更喜欢检查而不是异常的成本.
这个类TwigEngine有一个exists()方法,但没有找到使用的例子.
Nic*_*ich 65
如果配置为默认值,则持有twig引擎的服务是"模板化".
在Controller内部执行以下操作:
if ( $this->get('templating')->exists('AcmeDemoBundle:Foo:bar.html.twig') ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
替代方法是捕获异常render()方法抛出如下:
try {
$this->get('templating')->render('AcmeDemoBundle:Foo:bar.html.twig')
} catch (\Exception $ex) {
// your conditional code here.
}
Run Code Online (Sandbox Code Playgroud)
在普通的控制器......
$this->render('...')
Run Code Online (Sandbox Code Playgroud)
只是...的别名
$this->container->get('templating')->renderResponse($view, $parameters, $response);
Run Code Online (Sandbox Code Playgroud)
......而......
$this->get('...')
Run Code Online (Sandbox Code Playgroud)
...是别名
$this->container->get('...')
Run Code Online (Sandbox Code Playgroud)
看看Symfony\FrameworkBundle\Controller\Controller.
Jav*_*luz 22
该templating服务将在未来的Symfony版本中删除.基于该twig服务的面向未来的解决方案是:
if ($this->get('twig')->getLoader()->exists('AcmeDemoBundle:Foo:bar.html.twig')) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
小智 20
如果您需要从twig模板内部检查模板是否存在,则必须使用数组包含方法,如文档中所述:
{% include ['page_detailed.html', 'page.html'] %}
Run Code Online (Sandbox Code Playgroud)
小智 13
也许也是一个选择:
{% include 'AcmeDemoBundle:Foo:bar.html.twig' ignore missing %}
Run Code Online (Sandbox Code Playgroud)
当找不到模板时,忽略缺失添加会告诉twig什么都不做.