0

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 !

4
  • What version of twig are you using ? Commented Feb 7, 2020 at 14:48
  • 1
    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. Commented Feb 7, 2020 at 14:50
  • @Cid if i'm not mistaken, 4.2 Commented Feb 7, 2020 at 15:16
  • Thank you @Cerad, i'll look that way for now, if there's no better solution yet! Commented Feb 7, 2020 at 15:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your aswer ! I don't really to render any view ! I just want to know if the twig string is valid, get the value and pass it to Google API :) ! Next step after this is to send a request to Google so it replaces the twig string in their GDocs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.