Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

email - 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 the users can define something like "email templates" which are stores in db like simple string, for example: "This is some email from {{ user }}" and I need to render body for that email which should use that template...

In symfony documentation from this link: https://symfony.com/doc/2.0/cookbook/email/email.html#sending-emails the method for render view is $this->renderView and it expects the path to file such as "bundle:controller:file.html.twig", but my template is simple string from database...

How can I render it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...