Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count value in template expression

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?

like image 382
John Avatar asked Apr 17 '26 08:04

John


1 Answers

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»
    '''
}
like image 149
snorbi Avatar answered Apr 20 '26 00:04

snorbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!