Peter Rehm's Blog

apple,development,life & more

Symfony2 Render String with Twig

Ohne Kommentare

At some point you might find the need to render templates from an string rather
than an actual file. This is needed for dynamic templates.

This is not possible with the default Symfony2 configuration, however it is easy to
adjust the configuration.

I ended up adding the Twig_Loader_String to the Loader chain with teh following
service configuration:

CODE:
    newi.core.twig.stringloader:
        class: Twig_Loader_String
        tags:
            - { name: twig.loader }


With having this small snippet in the service.yml of one of your bundles you can
render strings with the normal twig instance from the DI container.

CODE:
    $renderedString = $this->get('twig')->render('Hello my name is {{ name }}!', array($name => 'Peter'));

Geschrieben von Peter Rehm

26.05.2014 um 13:32:35

Tags für diesen Artikel: , ,