Tibo
Tibo

Reputation: 197

Creating dynamic Twig template inside the PHP Controller with Symfony

To explain my needs :

I absolutely need to get the final value ("John"), because GDocs just gives a method to search and replace a string (search "{% if user.id is defind %}{{ user.name }}{% endif %}", replace by "John").

So...

For each twig string that I find in their GDocs, I need to test if I can find a value for this twig.

Is there a way to "create" a twig in my Controller, replace its value by something like this ?

$myTwig = new TwigTemplate("{% if user.id is defind %}{{ user.name }}{% endif %}");
$myUserName = $this->render($myTwig, array("user" => $user")

Thank you in advance !

Upvotes: 0

Views: 1019

Answers (1)

Cid
Cid

Reputation: 15257

You can use template_from_string() in twig to eval a string as twig code :

$myTwig = "{% if user.id is defind %}{{ user.name }}{% endif %}";
// $template can be the base template in which you inject the code
$myUserName = $this->render($template, array('myTwig' => $myTwig, "user" => $user");

In the view :

{{ include(template_from_string(myTwig)) }}

More informations in the documentation

Upvotes: 1

Related Questions