I want to count a value inside a template expression, in Xtend, without printing it out.
This is my code:
def generateTower(Tower in) {
var counter = 0.0;
'''
One Two Three Four
«FOR line : in.myTable»
«counter» «line.val1» «line.val2» «line.val3»
«counter = counter + 1»
«ENDFOR»
'''
}
So this will generate a table with four columns, whereas the first column is incremented starting at 0.0. The problem is, that «counter = counter + 1»
is printed as well. But I want the expression above to just count up, without printing it out.
What could be the best solution to solve this problem?
You could use this simple and readable solution:
«FOR line : in.myTable»
«counter++» «line.val1» «line.val2» «line.val3»
«ENDFOR»
If you insist on the separate increment expression, use a block with null
value. This works because the null
value is converted to empty string in template expressions (of course you could use ""
as well):
«FOR line : in.myTable»
«counter» «line.val1» «line.val2» «line.val3»
«{counter = counter + 1; null}»
«ENDFOR»
Although the first solution is the better. If you require complex logic in a template expression I recommend implementing it by methods not by inline code...
And finally, here is a more OO solution for the problem:
class TowerGenerator {
static val TAB = "\t"
def generateTower(Tower in) {
var counter = 0
'''
One«TAB»Two«TAB»Three«TAB»Four
«FOR line : in.myTable»
«generateLine(line, counter++)»
«ENDFOR»
'''
}
def private generateLine(Line line, int lineNumber) '''
«lineNumber»«TAB»«line.val1»«TAB»«line.val2»«TAB»«line.val3»
'''
}