7

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?

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):

  • 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)

Update 1:

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.

4

2 回答 2

6

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

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 似乎工作得很好!

于 2013-03-26T16:25:47.977 回答
2

这是临时更改标准环境中的加载程序的一种廉价而愉快的方式:

    // Keep the current loader
    $oldLoader = $env->getLoader();

    // Temporarily set a string loader   
    $env->setLoader(new \Twig_Loader_String());

    // Resolve the template - but don't render it yet.
    $template = $env->resolveTemplate($template);

    // Restore the old loader
    $env->setLoader($oldLoader);

    // Render the template. This will pass the old loader into any subtemplates and make sure your string based template gets into the cache.
    $result = $template->render($context);

我想这将适用于其他自定义加载程序。

于 2014-06-18T23:07:26.540 回答