繁体   English   中英

Symfony:有没有办法使用模板的相对路径渲染树枝模板?

[英]Symfony: Is there any way to render a twig template using a relative path to the template?

在Symfony文档的模板命名和位置部分中,它说:

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

  • AcmeBlogBu​​ndle:Blog:index.html.twig:此语法用于指定特定页面的模板。 字符串的三个部分,每个部分用冒号(:)分隔,表示以下内容:
  • AcmeBlogBu​​ndle :(包)模板存在于AcmeBlogBu​​ndle内(例如src / Acme / BlogBu​​ndle); Blog :(控制器)表示该模板位于Resources / views的Blog子目录中;
  • index.html.twig :(模板)文件的实际名称是index.html.twig。

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

// 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模板引擎提供相对或绝对路径一个twig模板,让它呈现它不必使用bundle:controller:template

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

例如 :

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

哪个应该允许你写:

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

要么

'@product/%s_description.html.twig'

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM