如何在 Symfony2 环境中注册另一个(自定义)Twig 加载器? [英] How to register another (custom) Twig loader in Symfony2 environment?

查看:26
本文介绍了如何在 Symfony2 环境中注册另一个(自定义)Twig 加载器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Symfony2 应用程序中从数据库加载某些 Twig 模板,同时仍然保留使用本机加载器在标准文件系统位置呈现模板的可能性.如何实现这一目标?

I would like to load certain Twig templates from the database in my Symfony2 application, while still keeping the possibility to use the native loader to render templates in the standard filesystem locations. How to achieve this?

据我所知,不可能向 Twig 环境注册多个加载器.我一直在思考两种方式(目前):

As far as I've understood, there is no possibility to register multiple loaders to Twig environment. I have been thinking two ways (for now):

  • 用自定义代理类替换默认加载器.当使用标准@Bundle-notation 引用模板时,代理会将请求传递给默认加载器.在其他情况下,请求将传递给我的自定义(数据库)加载器;或
  • 建立一个全新的 Twig 环境.此方法需要将自定义 Twig 扩展注册到两种环境,并且不允许交叉引用来自不同来源(一些来自 @Bundles,一些来自数据库)的模板
  • Replace the default loader with a custom proxy class. When templates are referred with the standard @Bundle-notation, proxy would pass the request to the default loader. In other case, the request would be passed to my custom (database) loader; OR
  • Build up a completely new Twig environment. This method would require registering custom Twig extensions to both environments and it does not allow cross-referencing templates from different sources (some from @Bundles, some from database)

更新 1:

似乎 Twig 支持 Twig_Loader_Chain 类可以在我的第一个选项中使用.尽管如此,默认加载器应该可以访问并作为第一个选项传递给链.

It seems that Twig supports Twig_Loader_Chain class that could be used in my first option. Still, the default loader should be accessible and passed to the chain as the first option.

推荐答案

要使用 Twig_Loader_Chain 你需要 Symfony 2.2https://github.com/symfony/symfony/pull/6131
然后你可以简单地配置你的加载器:

To use Twig_Loader_Chain you need Symfony 2.2 https://github.com/symfony/symfony/pull/6131
Then you can simply configurate your loaders:

services:
    twig.loader.filesystem:
        class: %twig.loader.filesystem.class%
        arguments:
            - @templating.locator
            - @templating.name_parser
        tags:
            - { name: twig.loader }
    twig.loader.string:
        class: %twig.loader.string.class%
        tags:
            - { name: twig.loader }

<小时>

更新:
看起来仍然存在一些问题(文件系统加载器有时找不到模板)但我发现了这个:
http://forum.symfony-project.org/viewtopic.php?t=40382&p=131254

看起来效果很好!


Update:
It looks like there are still some problems(the filesystem loader couldn't find the templates somtimes) but I found this:
http://forum.symfony-project.org/viewtopic.php?t=40382&p=131254

Seems to be working great!

这篇关于如何在 Symfony2 环境中注册另一个(自定义)Twig 加载器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆