【发布时间】:2013-05-21 00:35:53
【问题描述】:
有没有办法在调用渲染之前检查树枝模板是否存在?至少在开发环境中,try catch 块似乎不起作用,而且,我更喜欢检查而不是异常的成本。
这个类TwigEngine有一个exists()方法,但是没有找到使用的例子。
【问题讨论】:
标签: symfony twig transclusion
有没有办法在调用渲染之前检查树枝模板是否存在?至少在开发环境中,try catch 块似乎不起作用,而且,我更喜欢检查而不是异常的成本。
这个类TwigEngine有一个exists()方法,但是没有找到使用的例子。
【问题讨论】:
标签: symfony twig transclusion
如果配置为默认值,则持有 twig 引擎的服务是“模板”。
在您的 Controller 中执行以下操作:
if ( $this->get('templating')->exists('AcmeDemoBundle:Foo:bar.html.twig') ) {
// ...
}
另一种方法是捕获 render() 方法抛出的异常,如下所示:
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('...')
【讨论】:
$this->container->get('templating')->exists('@YourBundle/..Path../twigName.html.twig') 如果没有 $this->container,请改用 $this->getContainer()->...。
templating 服务将在未来的 Symfony 版本中被删除。基于twig 服务的面向未来的解决方案是:
if ($this->get('twig')->getLoader()->exists('AcmeDemoBundle:Foo:bar.html.twig')) {
// ...
}
【讨论】:
templating 服务将在未来的 Symfony 版本中被删除?
如果您需要从 twig 模板中检查模板是否存在,您必须使用数组包含方法,如 documentation 中所述:
{% include ['page_detailed.html', 'page.html'] %}
【讨论】:
{% include ['page_detailed.html', 'page.html', 'empty-catch-all.html'] %}
也许也是一种选择:
{% include 'AcmeDemoBundle:Foo:bar.html.twig' ignore missing %}
忽略缺失的添加告诉 twig 在找不到模板时什么也不做。
【讨论】:
你可以使用依赖注入来做到这一点:
use Symfony\Component\Templating\EngineInterface;
public function fooAction(EngineInterface $templeEngine)
{
if ($templeEngine->exists("@App/bar/foo.html.twig")) {
// ...
}
// ...
}
使用 Symfony 3.4 测试。
【讨论】:
您可以使用依赖注入来获取存储 Twig 配置的环境。像这样(在控制器中):
/**
* @Route("/{path}")
*/
public function index($path, Twig\Environment $env)
{
if (!$env->getLoader()->exists('pages/'.$path.'.html.twig')) {
return $this->render('pages/404.html.twig');
}
}
【讨论】: