Render content from string/database and generate l

2019-01-23 20:58发布

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 seams impossible to render content from a string. Twig only accepts files. My content may contain dynamic parts like locale or similar, so the render power of twig would be very useful.

I tried to render it using the TwibstringBundle, but its functionality is quite limited and it does not work with the path-function.

Any suggestions to work around the issue?

标签: symfony twig
3条回答
劫难
2楼-- · 2019-01-23 21:45

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'));
查看更多
萌系小妹纸
3楼-- · 2019-01-23 21:56

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']));
查看更多
倾城 Initia
4楼-- · 2019-01-23 21:57

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.

查看更多
登录 后发表回答