Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register another (custom) Twig loader in Symfony2 environment?

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.

like image 245
Ville Mattila Avatar asked Jan 15 '13 17:01

Ville Mattila


1 Answers

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 }

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!

like image 177
Juburin Avatar answered Sep 29 '22 20:09

Juburin