提问者:小点点

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


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

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

  • AcmeBlogBundle: Blog:index.html.twig:此语法用于指定特定页面的模板。字符串的三个部分,每个部分由冒号(:)分隔,表示以下内容:
  • AcmeBlogBundle:(bundle)模板位于AcmeBlogBundle(例如src/Acme/BlogBundle)内;Blog:(控制器)表示模板位于Resources/view的Blog子目录内;
  • index.html.twig:(模板)文件的实际名称index.html.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").

是的,我可以将产品描述模板移动到路径/到/捆绑/资源/视图/,但我更感兴趣的是是否有可能绕过这个约定:有没有一种方法给树枝模板引擎相对或绝对路径到树枝模板,并让它渲染它不一定要使用约定bundle: Controlers:模板


共2个答案

匿名用户

您也可以创建一个新的命名空间,如下所述: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'

匿名用户

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

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