[Question] How to print modified AST back to twig syntax? #3792
Replies: 8 comments
-
There is no AST printer in Twig (this is not a core use case, and adding support for it would probably add requirements on custom nodes as the Twig AST is extensible, so it is unlikely to be implemented in the core IMO) |
Beta Was this translation helpful? Give feedback.
-
Thanks for quick answer! |
Beta Was this translation helpful? Give feedback.
-
It would be next to impossible because the parsing to node conversion is a lossy process. Token parsers are basically just walking through the token stream and doing whatever they want with it, as they convert it to nodes. One thing nodes do have is knowledge of the line number the token began on, so if you’re OK with doing something a little hacky, you could just refer to the original |
Beta Was this translation helpful? Give feedback.
-
Indeed, to perform refactoring of the template, you would probably need a CST rather than an AST to preserve formatting. And you would indeed need a printer that knows about each kind of nodes, which is impossible in an extensible syntax tree unless each node is required to provide its own printing implementation. |
Beta Was this translation helpful? Give feedback.
-
@stof What does CST stand for? |
Beta Was this translation helpful? Give feedback.
-
@brandonkelly The line replacement sounds like a really good idea to try out, thanks. What experience do you have with such changes? |
Beta Was this translation helpful? Give feedback.
-
None, just thinking out loud :) Theoretically possible though, as nodes make their line number available via a public |
Beta Was this translation helpful? Give feedback.
-
@TomasVotruba it stands for Concrete Syntax Tree, i.e. a syntax tree that preserves all information about formatting, comments, etc... |
Beta Was this translation helpful? Give feedback.
-
Hi,
I'm trying to modify the Twig node with node visitors. I managed to do that, but I could not find a how to print the modified node back to Twig.
My goal is to change single item like following:
How can I achieve that?
Thank you
Beta Was this translation helpful? Give feedback.
All reactions