Render content from string/database and generate links with twig

前端 未结 3 1071
孤街浪徒
孤街浪徒 2020-12-09 23:30

Because of several reasons including translation of content i had to build a simple CMS to render the pages of my Symfony2 application.

My problem now is, that is se

相关标签:
3条回答
  • 2020-12-10 00:14

    twig_template_from_string function's source code is as follows:

    function twig_template_from_string(Twig_Environment $env, $template)
    {
        return $env->createTemplate($template);
    }
    

    It means that if you already have a twig environment then it's better to call directly:

    $template = $env->createTemplate($templateString);
    $parsedContent = $template->render(array('a'=>'b'));
    
    0 讨论(0)
  • 2020-12-10 00:18

    Symfony 2.7 makes this easy from PHP, too:

        $twig = $this->get('twig');
        $template = twig_template_from_string($twig, 'Hello, {{ name }}');
        $output = $template->render(['name' => 'Bob']));
    
    0 讨论(0)
  • 2020-12-10 00:22

    see http://twig.sensiolabs.org/doc/functions/template_from_string.html and http://symfony.com/doc/current/cookbook/templating/twig_extension.html#register-an-extension-as-a-service

    {% include template_from_string("Hello {{ name }}") %}
    {% include template_from_string(page.template) %}
    

    Since the string loader is not loaded by default, you need to add it to your config.

    # src/Acme/DemoBundle/Resources/config/services.yml
    acme.twig.extension.loader:
        class:        Twig_Extension_StringLoader
        tags:
             - { name: 'twig.extension' }
    

    Where Acme/acme is your application name and DemoBundle is the bundle you want to enable it for.

    0 讨论(0)
提交回复
热议问题