Comma Separated Lists in Velocity

July 11, 2013

I was creating a create table statement in a Velocity template. I wanted to put a comma on each column of the table apart from the last. With template languages like Django's, you can get access to forloop.last and test for this with an if. Velocity makes it more challenging.

Velocity Macro

The first thing to do is define a macro which will optionally add a comma. It will do this for all entries in the for loop apart from the last. It takes two parameters: the current position in the array, and the size of the array.

#macro(commaIfNeeded $index $size)
#set ( $lastone = $size - 1 ) #if( $index <= $lastone ),
#else #end
#end

Here's the snippet from the velocity template that builds up a create table statement with commas on all but the last column.

CREATE TABLE $table.name
(
#foreach ($column in $table.columns)
$column.name  column.oracleType $column.oracleNull #commaIfNeeded( $velocityCount $table.columnCount )
#end
);

Here's the simple implementation of getColumnCount, used as the second parameter. This is implemented on the class behind the table velocity context variable.

public int getColumnCount()
{
  return this.getColumns().size();
}

References

Tags: velocity macro