Analyze or alter templates using the Visitor pattern
mainFluid provides a Visitor pattern to inspect or modify the Abstract Syntax Tree (AST) of a template.
Visiting a template
Use Fluid.Ast.AstVisitor to traverse the template. This is useful for security checks (e.g., verifying if a specific identifier is accessed) or auditing.
Rewriting a template
Use Fluid.Ast.AstRewriter to create a new version of the template with modified nodes. For example, you can replace one filter with another (e.g., replacing plus with minus).
Automatic processing via TemplateParsed
To apply visitors or rewriters to all templates (including includes and partials) automatically, use the TemplateParsed callback on TemplateOptions. This ensures the modified version is cached, improving performance.
public class ReplacePlusFiltersVisitor : AstRewriter
{
protected override Expression VisitFilterExpression(FilterExpression filterExpression)
{
if (filterExpression.Name == "plus")
{
return new FilterExpression(filterExpression.Input, "minus", filterExpression.Parameters);
}
return filterExpression;
}
}
// Usage
var template = new FluidParser().Parse("{{ 1 | plus: 2 }}");
var visitor = new ReplacePlusFiltersVisitor();
var changed = visitor.VisitTemplate(template);
var result = changed.Render(); // writes -1