2
votes

I've already read How does Symfony2 detect where to load templates from? and another ton of articles on the web

The question was quite similar to mine, but the answer wasn't comprehensive.

I need to override a bundle-defined template inside another custom bundle. In other words I want specify another path where symfony have to look before looking in app/Resources when loading templates.

Workflow should be something like this:

first: /src/My/Bundle/Resources/views/example.html.twig (or /src/My/Bundle/OriginalBundle/views/example.html.twig)

then: /app/Resources/OriginalBundle/views/example.html.twig

finally: /src/Original/Bundle/Resources/views/example.html.twig

The standard app/Resources -> src/Original/Bundle isn't enough.

sorry for my poor english and thank you

3

3 Answers

5
votes

To add a directory for twig templates I do this:

chdir(__DIR__);
$this->container->get('twig.loader')->addPath('../../../../web/templates/', $namespace = '__main__');

this allows me to put twig templates in a folder called 'templates' in the web folder and symfony 2.3 has no issues loading them.

9
votes

There's a native feature to do exactly what you want in a nice way. Escentially you can add a twig namespace to the twig configuration in app/config.yml like this:

twig:
    # ...
    paths:
        "%kernel.root_dir%/../vendor/acme/foo-bar/templates": foo_bar

This creates an alias to the folder vendor/acme/foo-bar/templates and then you can use it to render your templates either from the controllers:

return $this->render(
    '@foo_bar/template.html.twig',
    $data
);

or from other twig templates

{% include '@foo_bar/template.html.twig' %}

Source: official cookbook http://symfony.com/doc/current/cookbook/templating/namespaced_paths.html

2
votes

The class responsible for loading twig templates is stored at the service id twig.loader, which by default is an instance of Symfony\Bundle\TwigBundle\Loader\FilesystemLoader, and the class for locating templates is stored at the service id templating.locator and by default is an instance of the class Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator (which itself is injected as the first parameter to twig.loader)

So, in theory, all you would need to do is write your own class that implements Symfony\Component\Config\FileLocatorInterface (or extends Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator) and then inform the configuration to use your class (which I was going to look up how to do this for you, but Symfony's websites are down right now)