I`m working on an email template system. Scenario: In a textarea user is composing an email template, he can use text and twig so he can usee loops , condition blocks, variables etc. Then the user saves a template to the database. Before that, the template is validated form a twig structure perspective. Then we can load a template from the database (string), extract all necessary variables and as a service for it. After service returns all necessary variables I inject it into template and send an email.
For instance, the template can look like this
Hello {% if gender == 'm' %}Ms.{% else %}Mrs.{% endif% } {{name}}
Bla bla bla {{variable}} bla bla bal {{variable2}}
So basically I want to extract all variables names from a string.
I can create a twig template straight from a database by:
$template = $this->twig->createTemplate($templateFromDatabase);
I can get tokens by
$tokens = $twig->tokenize($source);
but it doesn`t tell me which tokens are variables
Finally, I can parse it and go through structure and extract variables.
$parsed = $twig->parse($tokens);
But maybe there is an easier way to get all variables names from a template. Also, do you know a way to validate twig template before saving to the database ?
Also, I`m creating a service in Symfony to handle all of that and return complete email template ready to sent so I can use a PHP twig functions
Or maybe there is already bundle or something like that (i didnt find anything) Thanks in advance