How to get all the variables of a template
Hello Guys,
First of all, thank you for your incredible work here !
I am using this lib within an api and I want to implement a function which takes in argument the twig template and return the list of the variables needed to compile/render the twig.
I have been looking at the source code to find any way to achieve this, but so far I didn't find any solution. Did someone already implemented this kind of function ?
Thank you.
Hi @benjaminSe1,
I think your best bet would be to use the included Twig parser to get the nodes that your template is made of, and isolate the nodes that handle the variable assignment. It should be easy enough.
You can start by looking at that project I wrote some time ago, that transpiles Twig template to PHTML templates. To achieve this, it uses Twing parser to walk through the nodes:
https://github.com/NightlyCommit/twig-to-phtml
The parts that may be of interest to you are:
https://github.com/NightlyCommit/twig-to-phtml/blob/c70eb15f9279a16e4450b1c899d0b1a5736d5b24/src/lib/Transpiler.ts#L509
https://github.com/NightlyCommit/twig-to-phtml/blob/c70eb15f9279a16e4450b1c899d0b1a5736d5b24/src/lib/Transpiler.ts#L205
With Twing, the nodes that handle variables (both assignment ans output) are node instanceof TwingNodeExpressionName and TwingNodeExpressionAssignName.
This should be a fun tool to write actually. Let me know how it goes.