velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Holger Willebrandt <>
Subject Collect variables from a template
Date Wed, 15 Mar 2006 10:07:56 GMT
Hello everybody,

i would like to parse a velocity template and collect information about
all variables that are used within it.
Therefore, i use the Parser class in the following way:

//here a reader for the template and a collector for the variables
//will be supplied
public static void findVariables(Reader reader, List collector)
		throws ParseException {
	VelocityCharStream cstream = new VelocityCharStream(reader, 0, 0);
	Parser parser = new Parser(cstream);
	findVariables(parser.process(), collector); //call method below

//this method will recursively collect the variables and store them
//in the collector.
public static void findVariables(Node startNode, List collector) {
	if (startNode.getClass().equals(ASTReference.class)) {
		if (!collector.contains(startNode.literal())) {
	for (int i = 0; i < startNode.jjtGetNumChildren(); i++) {
		findVariables(startNode.jjtGetChild(i), collector);

The code is working as long as the template does not contain a #foreach statement.
Whenever i try to parse velocity code with a #foreach, i get the following error:

         at org.apache.velocity.runtime.parser.Parser.Directive(
         at org.apache.velocity.runtime.parser.Parser.Statement(
         at org.apache.velocity.runtime.parser.Parser.process(

Looking into velocity's source code, revealed that the Parser is missing a 
RuntimeServices instance, resp. a template name.

It would be nice to have a way of collecting all variables and validating the 
synatx (a ParseException would indicate a syntax error) at once.

Any kind of help or advice is welcome.

Thanks, Holger

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message