将Twig模板呈现为字符串,添加自定义资产路径

时间:2015-06-28 17:27:16

标签: image symfony twig assets

我们的项目允许用户创建自定义主题文件。由于项目的结构方式,我们必须渲染这些文件并保存输出。该项目使用Symfony2。

为了渲染这个Twig模板并将输出保存到另一个文件,我使用一个以@templating为参数的服务。

services.yml定义了这样的服务:

private static final long serialVersionUID = XXXL;

这给了我一个TwigEngine对象,我可以这样使用:

    theme_renderer:
  class: ApiBundle\Service\ThemeRenderer
  arguments: [ @templating ]

这很好用。

但是,如果模板包含{{asset('images','some_image')}}标记,则渲染将失败。例外是:

public function __construct(TwigEngine $templateEngine) {
    $this->templateEngine = $templateEngine;
}

public function renderTheme($filePath, $themeSettings) {
    ...
    $renderedFileContents = $this->templateEngine->render($sourceFilePath, $themeSettings);
    ...
}

我需要能够为asset()标记的呈现提供自定义(CDN实际)URL。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

我认为异常消息There is no "some_image" asset package.很明确。 asset函数的第二个参数是包名。模板组件的包在Symfony配置中的framework.templating键下定义(等.config.yml)。

http://symfony.com/doc/current/reference/configuration/framework.html#packages

# app/config/config.yml
framework:
    # ...
    templating:
        packages:
            avatars:
                base_urls: 'http://static_cdn.example.com/avatars'

然后您可以使用asset('my_image.jpg', 'avatars')。所以,我想你没有定义包some_image或者配置不正确。