Symfony Load Twig Template From String

As is always the case with PHP, or open source technology, there’s a gazillion ways to rule the world, or solve a problem. I had a problem with a Symfony app I was building. I needed to load the Twig template from a string variable rather than a file.

To do so is easy. All you have to do is activate the Twig_String_Loader extension and use template_from_string to load it.

I’m dynamically creating a SOAP request, inserting the proper user credentials on the fly. To do that I created a template called soap-request with this in it.

{{ include(template_from_string(xml)) }}

Before that can work, the Twig_String_Loader needs to be loaded. You can do that in app/config/services.yml, or wherever you configure services.

my.twig.extension.loader:
    class: Twig_Extension_StringLoader
    tags:
       - { name: 'twig.extension' }

There are other convoluted ways to load the Twig_String_Loader, but this is the cleanest most Symfony-esque way to do it.

In my controller I do something like this.

$options = array(
  'username'=>'doser',
  'password'=>'moser',
  'xml'=>$data['xml']
);

$payload = $this->renderView('MyBundle:Default:soap-request.html.twig', $options);

The $data[‘xml’] is a SOAP request that has some tokens in it like {{ username }} and {{ password }}. In soap-request.html.twig, the include(template_from_string(xml)) handles variable interpolation. Then $payload contains a the SOAP request I want with the username and password set.

Share Button