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

Rendering a Twig template to string, adding custom asset path

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

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

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

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

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

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

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

这很好用。

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

An exception has been thrown during the rendering of a template ("There is no "some_image" asset package.") in "<template_file_path_here>" at line 2

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

我认为异常消息 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 或者配置不当。