Skip to content

How to Use and Register Namespaced Twig Paths

Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

Usually, when you refer to a template, you'll use the Twig namespaced paths, which are automatically registered for your bundles:

1
2
{% extends "@App/layout.html.twig" %}
{{ include('@App/Foo/bar.html.twig') }}

Note

In the past, Symfony used a different syntax to refer to templates. This format, which uses colons (:) to separate each template path section, is less consistent and has worse performance than the Twig syntax. For reference purposes, this is the equivalent notation of the previous example:

1
2
3
{# the following template syntax is no longer recommended #}
{% extends "AppBundle::layout.html.twig" %}
{{ include('AppBundle:Foo:bar.html.twig') }}

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-bar/templates. First, register a namespace for this directory:

1
2
3
4
5
# app/config/config.yml
twig:
    # ...
    paths:
        '%kernel.project_dir%/vendor/acme/foo-bar/templates': foo_bar

The registered namespace is called foo_bar, which refers to the vendor/acme/foo-bar/templates directory. Assuming there's a file called sidebar.twig in that directory, you can use it as follows:

1
{{ include('@foo_bar/sidebar.twig') }}

Multiple Paths per Namespace

You can also assign several paths to the same template namespace. The order in which paths are configured is very important, because Twig will always load the first template that exists, starting from the first configured path. This feature can be used as a fallback mechanism to load generic templates when the specific template doesn't exist.

1
2
3
4
5
6
7
# app/config/config.yml
twig:
    # ...
    paths:
        '%kernel.project_dir%/vendor/acme/themes/theme1': theme
        '%kernel.project_dir%/vendor/acme/themes/theme2': theme
        '%kernel.project_dir%/vendor/acme/themes/common': theme

Now, you can use the same @theme namespace to refer to any template located in the previous three directories:

1
{{ include('@theme/header.twig') }}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version