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 {% verbatim %}{{ name }}{% endverbatim %}', $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();
On this page

Last updated on 20/10/2026 by Anonymous