samskivert / jmustache

A Java implementation of the Mustache templating language.
Other
834 stars 128 forks source link

Get all template parameters #108

Closed meirf closed 5 years ago

meirf commented 5 years ago

As an example, for a template like:

The {{pet}} chased after the {{toy}}

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?

samskivert commented 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); }
});
samskivert commented 5 years ago

Also, FYI, this is not an issue with JMustache, this is a "how to use it" question which is more appropriate for Stack Overflow.

MichalFoksa commented 4 years ago

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; }
});