I'm attempting to use StringTemplate.v4 for simplistic templates, meaning only simple gaps names like %body%
--I'm not using any other features, such as if-logic, sub-templates, or expressions.
(To be honest, it's API is poorly documented, and at this point I'm considering abandoning it completely. It would be nice if there were JavaDoc source code links, so at least I could dig around and figure things out myself. Really frustrated.)
I'm trying to determine the gaps that exist in an anonymous template, to verify it has the required gaps before attempting to use it.
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.compiler.FormalArgument;
public class GapsInAnST {
public static final void main(String[] ignored) {
ST tmpl = new ST("Hello %name%. You are %age% years old.", '%', '%');
Map<String,Object> gapMap = tmpl.getAttributes();
System.out.println("gapMap=" + gapMap);
if(gapMap != null) {
System.out.println("getAttributes()=" + Arrays.toString(gapMap.keySet().toArray()));
}
System.out.println("tmpl.impl.hasFormalArgs=" + tmpl.impl.hasFormalArgs);
Map<String,FormalArgument> formalArgMap = tmpl.impl.formalArguments;
if(formalArgMap != null) {
System.out.println("getAttributes()=" + Arrays.toString(formalArgMap.keySet().toArray()));
}
tmpl.add("name", "Seymour");
tmpl.add("age", "43");
System.out.println(tmpl.render());
}
}
Output:
gapMap=null
tmpl.impl.hasFormalArgs=false
Hello Seymour. You are 43 years old.
I found out why getAttributes()
returns null
in this google groups thread, and about formalArguments
in this question: StringTemplate list of attributes defined for a given template).
So how do I get all gaps actually existing in an anonymous template before filling any gaps? I realize I could do it with regex, but I am hoping there is a built in way of doing this.
Thanks.