Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Twig: Default template file in custom location

Tags:

php

twig

symfony

I try to load a simple base.html.twig template file that was moved from symfony's default location app/Resources/views/ to the custom location theme/.

The template file contains:

    <!DOCTYPE html>
    <html>
     <head>
     ...
     </head>
     <body>
      {% block body %}{% endblock %}
     </body>
    </html>

Extending the above template file by the controller Acme\Core\CoreBundle\Controller by using the controller-specific template

    {% extends '::base.html.twig' %}
    {% block body %}
      Hello world!
    {% endblock %}

leads to an error saying Unable to find template "::base.html.twig" in "AcmeCoreCoreBundle:Default:index.html.twig"..

How is it possible to tell symfony where to find the template files in global space?

Thanks in advance.

like image 848
dnl Avatar asked Oct 18 '12 10:10

dnl


1 Answers

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

like image 140
Miguel Trias Avatar answered Sep 28 '22 08:09

Miguel Trias