define custom filesystem path for twig templates

前端 未结 3 1486
攒了一身酷
攒了一身酷 2020-12-21 14:07

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 answ

相关标签:
3条回答
  • 2020-12-21 14:11

    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.

    0 讨论(0)
  • 2020-12-21 14:11

    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

    0 讨论(0)
  • 2020-12-21 14:36

    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)

    0 讨论(0)
提交回复
热议问题