Symfony2:Twig:自定义位置的默认模板文件

2022-01-22 00:00:00 php symfony twig

我尝试加载一个简单的 base.html.twig 模板文件,该模板文件已从 symfony 的默认位置 app/Resources/views/ 移动到自定义位置 主题/.

I try to load a simple base.html.twig template file that was moved from symfony's default location app/Resources/views/ to the custom location theme/.

模板文件包含:

    <!DOCTYPE html>
    <html>
     <head>
     ...
     </head>
     <body>
      {% block body %}{% endblock %}
     </body>
    </html>

通过控制器扩展上述模板文件AcmeCoreCoreBundleController 使用控制器特定的模板

Extending the above template file by the controller AcmeCoreCoreBundleController by using the controller-specific template

    {% extends '::base.html.twig' %}
    {% block body %}
      Hello world!
    {% endblock %}

导致错误提示 Unable to find template "::base.html.twig" in "AcmeCoreCoreBundle:Default:index.html.twig"..

如何告诉 symfony 在全局空间中哪里可以找到模板文件?

How is it possible to tell symfony where to find the template files in global space?

提前致谢.

推荐答案

由于 Adam 的提示,我能够自己回答这个问题.所以如果有人感兴趣,我想提供我的答案.

Due to Adam's hint I am able to answer the question on my own. So I want to provide my answer if anybody is interested in.

AcmeDemoBundle 提供了一个可以简单使用的 twig 扩展(类 AcmeDemoBundleTwigExtensionDemoExtension).将构造函数更改为

The AcmeDemoBundle provides a twig extension (class AcmeDemoBundleTwigExtensionDemoExtension) that you simply can use. Change the constructor to

    public function __construct(FilesystemLoader $loader)
    {
     $this->loader = $loader;
     $this->loader->addPath('path/to/your/directory');
    }

现在告诉 symfony 注册 twig 扩展.编辑您的 config.yml 文件(例如 app/config/config.yml)并追加

Now tell symfony to register the twig extension. Edit your config.yml file (e.g. app/config/config.yml) and append

    services:
     demo.twig.extension
      class: AcmeDemoBundleTwigExtensionDemoExtension
      tags:
       - { name: twig.extension }
      arguments:
       - @Twig.loader

最后但并非最不重要的一点是更改扩展的树枝文件并从默认模板的命名空间中删除 :::{% extends 'base.html.twig' %}.

Last but not least change your extending twig file and remove the :: from your default template's namespace: {% extends 'base.html.twig' %}.

相关文章