Closed meirf closed 5 years ago
There is. Use the Template.visit()
method, which will give you a callback for every variable, include, section and inverted section. Something like:
List<String> vars = new ArrayList<>();
Template tmpl = ... // compile your template
tmpl.visit(new Template.Visitor() {
// I assume you don't care about the raw text or include directives
public void visitText (String text) {}
public void visitInclude (String name) {}
// You do care about variables, per your example
public void visitVariable (String name) { vars.add(name); }
// I assume you also care about sections and inverted sections
public void visitSection (String name) { vars.add(name); }
public void visitInvertedSection (String name) { vars.add(name); }
});
Also, FYI, this is not an issue with JMustache, this is a "how to use it" question which is more appropriate for Stack Overflow.
Hey @samskivert Found your example useful, unfortunately it is buggy. Can you PLS fix it so that others have it easier? Issues:
Modified example:
List<String> vars = new ArrayList<>();
Template tmpl = ... // compile your template
tmpl.visit(new Mustache.Visitor() {
// I assume you don't care about the raw text or include directives
public void visitText(String text) {}
// You do care about variables, per your example
public void visitVariable(String name) {vars.add("Variable: " + name); }
// Also makes sense to visit nested templates.
public boolean visitInclude(String name) { vars.add("Include: " + name); return true; }
// I assume you also care about sections and inverted sections
public boolean visitSection(String name) { vars.add("Section: " + name); return true; }
public boolean visitInvertedSection(String name) { vars.add("Inverted Section: " + name); return true; }
});
As an example, for a template like:
I'd like to get ["pet", "toy"]
Is there a way to do this with jmustache so that I don't have to parse the string with a regex?