Twig Service

Derafu\Twig\Service\TwigService creates the Twig environment the first time that it is needed, and renders templates with it. Derafu\Twig\Service\TwigCreator creates the environment from its options and gives it back, without rendering.

Options

use Derafu\Twig\Service\TwigService;

$twig = new TwigService([
    'paths' => [__DIR__ . '/templates'],
    'extensions' => [new MyExtension()],
    'components' => [MyComponent::class],
    'extra' => true,
]);
Option Value Default
paths A directory, or a list of directories, where the templates are searched. The templates directory of the project, if it has one; none if it does not.
extensions The Twig extensions to add. None.
components The Symfony UX Twig Components to register: their classes, their instances or a provider (see Components). None.
extra true adds the extensions that depend on what is installed. true.

The project is the root package of Composer: the application that is running.

TwigService also takes an Environment that you created, or a TwigCreatorInterface, instead of the options. With an Environment, the service renders with it as it is.

The Extensions That Are Always There

The environment always has the TranslationExtension, so the templates can use trans without any setup. If you give your own, with a translator, that is the one that is used.

With extra the environment also has MarkdownExtension (see Extensions) and the Twig extensions that are installed: twig/cssinliner-extra, twig/intl-extra, twig/string-extra and twig/inky-extra.

Rendering

$data = ['name' => 'World'];

$twig->render('hello', $data);                 // templates/hello.html.twig.
$twig->render('hello.html.twig', $data);       // The same.
$twig->render('/other/place/page', $data);     // A template by its path: the directory is added to the paths.
$twig->renderFromString('Hello {{ name }}', $data);

A name without the extension .twig has .html.twig added. A template that is given with its absolute path is found in its directory, and the directory is added to the paths of the environment once.

The Environment

getTwig() gives the Twig\Environment, for the code that has to work with the templates themselves, for example the lint tools:

$environment = $twig->getTwig();

Dependency Injection

Import the real package configuration to obtain TwigCreatorInterface, TwigServiceInterface and ComponentRegistrarInterface:

imports:
    - { resource: '../vendor/derafu/twig/resources/config/twig-services.yaml' }

parameters:
    derafu.twig.options:
        paths: ['%kernel.project_dir%/templates']
        extra: true

Inject Derafu\Twig\Contract\TwigServiceInterface into the consumer. If paths is omitted, the project-template discovery described above remains in use. The creator’s configuration comes from derafu.twig.options. The component registrar’s cache-key prefix is derafu.twig.component_registrar.cache_key; an application PSR-6 pool registered under Psr\Cache\CacheItemPoolInterface is used when available, otherwise the registrar uses its file-cache default.

In DI configuration, keep paths and flags in parameters. Supply extensions through providers tagged derafu_twig.extension_provider, and components through providers tagged derafu_twig.component_provider. See Extensions and Components. The explicit PHP extensions and components options remain supported for construction without DI.

Provider collections are evaluated when the environment is created, not when the creator or service is constructed. An extension provider can depend on the Twig service as long as it does not request the environment in its constructor.

Using an Existing Environment

The service can wrap an environment created by Symfony or another consumer. For Symfony’s existing twig service, override only this interface registration after the package import:

services:
    Derafu\Twig\Contract\TwigServiceInterface:
        class: Derafu\Twig\Service\TwigService
        arguments:
            $twig: '@twig'

That exact environment is used. Its loader, globals, options and extensions are preserved. The package creator and its providers are not applied to an existing environment. For Symfony-managed components and extensions, use their native bundle integration rather than registering a second environment implicitly.

Independent Environments

A consumer may define another creator and service using qualified interface IDs. The default service remains available, and each service creates its own environment. For example, an email renderer with a separate template directory and provider tags:

parameters:
    derafu.twig.email_options:
        paths: ['%kernel.project_dir%/templates/email']
        extra: false

services:
    Derafu\Twig\Contract\TwigCreatorInterface $emails:
        parent: Derafu\Twig\Contract\TwigCreatorInterface
        arguments:
            $options: '%derafu.twig.email_options%'
            $extensionProviders: !tagged_iterator app.email_extension_provider
            $componentProviders: !tagged_iterator app.email_component_provider

    Derafu\Twig\Contract\TwigServiceInterface $emails:
        parent: Derafu\Twig\Contract\TwigServiceInterface
        arguments:
            $twig: '@Derafu\Twig\Contract\TwigCreatorInterface $emails'

The extension and component collections are separate from the default environment. An empty extension collection uses the built-in default provider; extra: false keeps translation support without the extra extensions. With a custom nonempty extension collection, include DefaultExtensionProvider in that collection if those default extensions are wanted too. Templates may be rendered through the explicitly selected service without replacing the application’s Twig environment.

Template Path Providers

Libraries can contribute their template roots without replacing the directories of another library or of the application. Implement Derafu\Twig\Contract\TemplatePathProviderInterface and tag each provider with derafu_twig.template_path_provider:

namespace Acme\Reports;

use Derafu\Twig\Contract\TemplatePathProviderInterface;

final class ReportTemplatePathProvider implements TemplatePathProviderInterface
{
    public function getPaths(): array
    {
        return [dirname(__DIR__) . '/resources/templates'];
    }
}
services:
    Acme\Reports\ReportTemplatePathProvider:
        tags:
            - { name: derafu_twig.template_path_provider, priority: 0 }

The production YAML registers TemplatePathProviderInterface using ChainTemplatePathProvider. It gathers paths in descending tag-priority order, removes repeated directory strings while keeping their first position, and preserves each provider’s internal order. It does not normalize or silently skip invalid contributed directories: Twig’s loader still validates them.

Providers are evaluated when the environment is created. If there are contributed paths, they supply the search roots; if there are none and no explicit paths, project-template discovery remains available. Explicit PHP or configured paths are searched first, followed by contributed roots. A library therefore contributes only its own directories instead of rebuilding a shared paths option.

A qualified independent creator can receive a different TemplatePathProviderInterface through its $templatePathProvider argument. This keeps private templates isolated without changing the default environment. Existing external Twig environments are still left untouched.

On this page

Last updated on 09/11/2026 by Anonymous