sebastienros / fluid

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

Introspection of parsed template using visitor #705

Open knightmeister opened 1 month ago

knightmeister commented 1 month ago

Hi,

I raised #578 and submitted a PR that received no comment and it looks like the advice now is to use the Visitor supports that's been recently added.

There is an example in the readme but it doesn't demonstrate what I need to do.

I need to walk the template and find instances of a given tag (in my case, {% layout '[id]' %}).

I want to be able to extract both the tag name (layout) and the input ID.

How do I do that using a Visitor?

Starting with a contrived example:

static void Main(string[] args)
{
    var template = new MyParser().Parse("{% layout 'layoutid' %}");
    var v = new Visitor();
    v.VisitTemplate(template);
}

public class Visitor : AstVisitor
{
    public override Statement Visit(Statement statement)
    {
        return base.Visit(statement);
    }
}

The Statement method breakpoints but I'm unable to access anything on the statement that is passed in. The only method is WriteToAsync and there are no properties.

How do I extract the statement name and passed parameter?

Cheers

sebastienros commented 1 month ago

I will check that. From a brief look at the source the layout tag is of type ParserTagStatement. Maybe filtering statements for this type and then casting would allow you to access the expression it links to. Not sure if this type is public yet.

knightmeister commented 1 month ago

Thanks Can't cast to ParserTagStatement because the ParserTagStatement is not exposed publicly.