How to render Twig template from database in symfony2

前端 未结 11 1000
闹比i
闹比i 2020-12-08 04:21

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 template

11条回答
  •  借酒劲吻你
    2020-12-08 05:16

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

提交回复
热议问题