How to use and Register namespaced Twig Paths
Edit this pageWarning: You are browsing the documentation for Symfony 2.2, which is no longer maintained.
Read the updated version of this page for Symfony 6.2 (the current stable version).
How to use and Register namespaced Twig Paths
2.2
Namespaced path support was added in 2.2.
Usually, when you refer to a template, you'll use the MyBundle:Subdir:filename.html.twig
format (see Creating and using Templates).
Twig also natively offers a feature called "namespaced paths", and support is built-in automatically for all of your bundles.
Take the following paths as an example:
1 2
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% include "AcmeDemoBundle:Foo:bar.html.twig" %}
With namespaced paths, the following works as well:
1 2
{% extends "@AcmeDemo/layout.html.twig" %}
{% include "@AcmeDemo/Foo/bar.html.twig" %}
Both paths are valid and functional by default in Symfony2.
Tip
As an added bonus, the namespaced syntax is faster.
Registering your own namespaces
You can also register your own custom namespaces. Suppose that you're using
some third-party library that includes Twig templates that live in
vendor/acme/foo-project/templates
. First, register a namespace for this
directory:
- YAML
- XML
- PHP
1 2 3 4 5
# app/config/config.yml
twig:
# ...
paths:
"%kernel.root_dir%/../vendor/acme/foo-bar/templates": foo_bar
1 2 3 4 5 6 7 8 9 10 11
<!-- app/config/config.xml -->
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:twig="http://symfony.com/schema/dic/twig"
>
<twig:config debug="%kernel.debug%" strict-variables="%kernel.debug%">
<twig:path namespace="foo_bar">%kernel.root_dir%/../vendor/acme/foo-bar/templates</twig:path>
</twig:config>
</container>
1 2 3 4 5 6
// app/config/config.php
$container->loadFromExtension('twig', array(
'paths' => array(
'%kernel.root_dir%/../vendor/acme/foo-bar/templates' => 'foo_bar',
);
));
The registered namespace is called foo_bar
, which refers to the
vendor/acme/foo-project/templates
directory. Assuming there's a file
called sidebar.twig
in that directory, you can use it easily:
1
{% include '@foo_bar/side.bar.twig` %}