Karol Fiturski Karol Fiturski - 1 month ago 34
Twig Question

How to render Twig template from database in symfony2

I'm working on application written in symfony2 and I want to send email after some action/event... the problem is, that users can definig something like "email templates" which stores in db like simple string, for example: "This is some email from {{ user }}" and I need to render body for email from that template...
In symfony documentation from this link: http://symfony.com/doc/2.0/cookbook/email.html#sending-emails the methos for render is $this->renderView and it expects reference to file as "bundle:controller:file.html.twig", but my template is database as simple string...
How can I render it?

Answer

Twig_Loader_String is deprecated and was always designed for internal use anyway. The usage of this loader is strongly discouraged.

From the API doc:

This loader should NEVER be used. It only exists for Twig internal purposes. When using this loader with a cache mechanism, you should know that a new cache key is generated each time a template content "changes" (the cache key being the source code of the template). If you don't want to see your cache grows out of control, you need to take care of clearing the old cache file by yourself.

Also check out this issue: https://github.com/symfony/symfony/issues/10865


The best way I know to load a template from a String source are:

From a controller:

$template = $this->get('twig')->createTemplate('Hello {{ name }}');
$template->render(array('name'=>'World'));

as described here: http://twig.sensiolabs.org/doc/recipes.html#loading-a-template-from-a-string

From a twig template:

{{ include(template_from_string("Hello {{ name }}", {'name' : 'Peter'})) }}

as described here: http://twig.sensiolabs.org/doc/functions/template_from_string.html

Note, that the 'template_from_string' - function is not available by default and needs to be loaded. In symfony you would do this by adding a new service:

# services.yml
services:
    appbundle.twig.extension.string:
        class: Twig_Extension_StringLoader
        tags:
            - { name: 'twig.extension' }