【问题标题】:Symfony: Is there any way to render a twig template using a relative path to the template?Symfony:有没有办法使用模板的相对路径来渲染树枝模板?
【发布时间】:2014-03-29 17:46:45
【问题描述】:

在 Symfony 文档的 Template Naming and Locations 部分中它说:

Symfony2 使用 bundle:controller:template 字符串语法 模板。这允许几种不同类型的模板,每个 居住在特定位置:

  • AcmeBlogBu​​ndle:Blog:index.html.twig:此语法用于指定特定页面的模板。字符串的三个部分,每个部分 用冒号 (:) 隔开,含义如下:
  • AcmeBlogBu​​ndle:(捆绑)模板位于 AcmeBlogBu​​ndle 中(例如 src/Acme/BlogBu​​ndle);博客:(控制器) 表示模板位于 Blog 的子目录中 资源/观点;
  • index.html.twig:(模板)文件的实际名称是 index.html.twig。

我想在我的数据夹具引导过程中解析一个 twig 模板并将 html 持久化到一个学说实体的属性中,如下所示:

// let's say it finds ./Data/Product/camera_description.html.twig
$productDescriptionTemplate = __DIR__.sprintf(
    '/Data/Product/%s_description.html.twig', 
    $product->getName()
);

$product->setDescription(
    $this->container->get('templating')->render(
        $productDescriptionTemplate, 
        array()
    )
);

$em->flush();

这会引发以下异常:

# would actually be an absolute path
[InvalidArgumentException]
  Template name "./Data/Product/camera_description.html.twig 
  " is not valid (format is "bundle:section:template.format.engine").

是的,我可以将产品描述模板移动到 path/to/bundle/Resources/views/,但我更感兴趣的是是否可以规避这个约定:有没有办法让 twig 模板引擎相对或绝对 树枝模板的路径并让它渲染它没有使用约定bundle:controller:template?

【问题讨论】:

标签: php symfony twig


【解决方案1】:

您还可以创建一个新的命名空间,如下所述:http://symfony.com/doc/current/cookbook/templating/namespaced_paths.html

例如:

paths:
        "%kernel.root_dir%/../Data/Product/": product

应该允许你写:

'product::%s_description.html.twig', 

'@product/%s_description.html.twig'

【讨论】:

【解决方案2】:

如果您不想使用bundle:controller:template 语法,那么您可以尝试直接使用twig

$product->setDescription(
    $this->container->get('twig')->render(
        $productDescriptionTemplate, 
        array()
    )
);

【讨论】:

  • 我试过这个并收到与原帖中提到的相同的异常。
猜你喜欢
  • 1970-01-01
  • 2012-07-27
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2012-04-28
相关资源
最近更新 更多