sebastienros / fluid

Fluid is an open-source .NET template engine based on the Liquid template language.
MIT License
1.42k stars 176 forks source link

Question: Get parsed member list from a template? #492

Open marlon-tucker opened 2 years ago

marlon-tucker commented 2 years ago

Hello,

Is there any way to get a list of members contained in a template.

For example, the template Hello {{ Firstname }} {{ Lastname }}, I need a way to get the strings "Firstname" and "Lastname".

If there's no built in method, would you consider having a AST visitor pattern in the project? A visitor is heavily tied to the AST so it makes sense for it to be in the same project.

Thanks

Marlon

hishamco commented 2 years ago

Did you dig into a MemberAccessor

marlon-tucker commented 2 years ago

Searching for MemberAccessor didn't return any results, only two issues. Any chance you can link to what you mean please?

hishamco commented 2 years ago

There's few typed for access members, please check https://github.com/sebastienros/fluid/tree/e6156835028b91e71634311076060ee75bfe5f6b/Fluid probably one of them achieve what you want

I'm busy with another PR, if I got a time I may look too

marlon-tucker commented 2 years ago

Those appear to be for getting a parsed value from a given model.

I suppose I could clear the IMemberAccessor collection and add a custom one that keeps track of all the member names it is asked to access, but doing that feels like I'm abusing the code a little.

It looks like an AST visitor will be needed. If I get time I'll see if I can submit a PR.

sebastienros commented 1 year ago

I agree there is a need for something like a visitor. I have had the need recently to be able to find in a node has subnodes of a specific type (example: in a for loop, is there any tag that uses the forloop object).

caspertl commented 1 year ago

I did this with custom code. But this wasn't easy :D look at

           var template = FluidParser.Parse(content);
           var statements = ((Fluid.Parser.FluidTemplate)template).Statements;
marlon-tucker commented 1 year ago

I had a spare few hours today so I did the first pass at implementing an AST Visitor.

The code can be found here https://github.com/marlon-tucker/fluid/tree/AST-Visitor

If a project maintainer has any advice as to how I should go about implementing tests to cover my additions I would be very appreciative. Adding a test which covers each possible AST node type to confirm it is visited is going to take longer than implementing the visitor did in the first place.

But if that is what has to be done, so be it.