首页 文章

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

提问于
浏览
10

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

Symfony2使用bundle:controller:模板的模板字符串语法 . 这允许使用几种不同类型的模板,每种模板都位于特定位置:AcmeBlogBundle:Blog:index.html.twig:此语法用于指定特定页面的模板 . 字符串的三个部分,每个部分用冒号(:)分隔,表示以下内容:AcmeBlogBundle :( bundle)模板位于AcmeBlogBundle内(例如src / Acme / BlogBundle); 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/ 但是我更感兴趣的是是否有可能绕过这个约定:有没有办法给树枝模板引擎提供树枝模板的相对或绝对路径并让它不渲染它必须使用惯例 bundle:controller:template

2 回答

  • 7

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

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

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

相关问题