简体   繁体   中英

StringTemplate: increment value when if condition true

I want to find out if StringTemplate have/support incrementation of a number.
Situation is:

input: is an array of objects which have " isKey() and getName() " getter.
output should be ( i=0; IF !obj.getKey() THEN ps.setObject(i++,obj.getName)) ENDIF ):

ps.setObject(1,"Name");  
ps.setObject(2,"Name");  
ps.setObject(3,"Name");  
...

Currently I have next ST : <objs:{<if(it.key)><else>ps.setObject(<i>, <it.name;>);<"\\n"><endif>}>
And the output in case if 1st is key:

ps.setObject(2,"Name");  
ps.setObject(3,"Name");  
ps.setObject(4,"Name");  
...

Issue now I need to find a way to replace the 'i' with something which will be increment only when if condition is true.

PLS advice who faced this kind of issue!

In general, changing the state in response to ST's getting the state is not a good idea, so numbering non-key fields should happen in your model, before you start with the generation.

Add a getter for nonKeyIndex to the class of your model that hosts the name property. Go through all siblings, and number them as you need (ie starting from one and skipping the keys in your numbering). Now you can use this ST to produce the desired output:

<objs:{<if(it.key)><else>ps.setObject(<it.nonKeyIndex>, <it.name;>);<"\n"><endif>}>

Sometimes it may not be possible to add methods such as nonKeyIndex to your model classes. In such cases you should wrap your classes into view classes designed specifically to work with string template, and add the extra properties there:

public class ColumnView {
    private final Column c;
    private int nonKeyIdx;
    public ColumnView(Column c) {this.c = c;}
    public String getName() { return c.getName(); }
    public boolean getKey() { return c.getKey(); }
    public int getNonKeyIndex() { return nonKeyIdx; }
    public void setNonKeyIndex(int i) { nonKeyIdx = i; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM