5

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 is that is seems 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.

madc
  • 1,674
  • 2
  • 26
  • 41

3 Answers3

15

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.

Community
  • 1
  • 1
Heyflynn
  • 901
  • 10
  • 23
  • That looks very promising, thanks for the answer. I will check it later and report back. – madc Oct 15 '12 at 14:01
  • implemented it last night. only drawback I found so far is that any twig extension you call, also uses the string loader. Exceptions etc.. are not handled very well. The string loader is suggested not to be used externally as the results may not be as you expect (ie. extending, including etc..) – Heyflynn Oct 15 '12 at 17:32
  • 5
    added the new twig supported way to load strings as templates – Heyflynn Nov 29 '12 at 18:01
  • Thanks for the answer. Worked in Symfony 2.8. – Skylord123 Jan 08 '16 at 16:09
6

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']));
Tac Tacelosky
  • 3,165
  • 3
  • 27
  • 28
  • Why only Symfony 2.7? Works on Symfony 2.3 for me, too. – Philipp Rieber Jul 13 '15 at 09:49
  • 2
    Doesn't work for me. I get 'Attempted to call function "twig_template_from_string" from namespace "AppBundle\Controller"' However, this worked for me: `$this->get('twig')->createTemplate('Hello, {{ name }}');` – Atan Mar 17 '16 at 11:12
4

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'));
Turdaliev Nursultan
  • 2,538
  • 1
  • 22
  • 28