0
votes

To explain my needs :

  • I want my users to create by themselves a "twig template" with Google Docs
  • For example, if inside my user's GDocs there is {% if user.id is defind %}{{ user.name }}{% endif %}
  • I want, in my Controller, to get this string ("{% if user.id is defind %}{{ user.name }}{% endif %}")
  • Then check if this particular Twig string can be interpreted
  • If yes, get the real value of that twig string (let's say "John")
  • And then, in a the GDocs of my user, replace "{% if user.id is defind %}{{ user.name }}{% endif %}" by "John"

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 !

1
What version of twig are you using ? - Cid
You can sort of do this with what is known as a Twig ArrayLoader. One problem is that twig templates are "compiled" into php and then cached for performance issues. So if you try doing something like this in production then you need to be careful about your cache. - Cerad
@Cid if i'm not mistaken, 4.2 - Tibo
Thank you @Cerad, i'll look that way for now, if there's no better solution yet! - Tibo

1 Answers

1
votes

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