stringtemplatestringtemplate-4

I need to compare property values in StringTemplate


I have a list of tuples that I need to emit a C-like boolean expression from:

ranges = [('a','z'),('0','9'),('_','_')]

my template:

"$ranges:{'$it.0$'<=c&&c<='$it.1$'}; separator='||'$"

this outputs:

'a'<=c&&c<='z'||'0'<=c&&c<='9'||'_'<=c&&c<='_'

I would like to check if $it.0$ is the same as $it.1$ and output c==='$it.0$' in this case (in my example this would generate c==='_' for the last tuple). Is this possible?


Solution

  • You can't have any computation in the template (see Stringtemplate compare strings does not work).

    A possible way of getting around this would be to use a custom Range class, and store the functionality inside that. Then you could call a method on the range object that returned whether or not the from and to values are equal.

    $ranges:{ range | $if(range.fromToEqual)$c === '$range.from$'$else$'$range.from$' <= c && c <= '$range.to$'$endif$}; separator=" || "$
    

    where the method in the Range class is as follows:

    public boolean getFromToEqual() { // note the 'get' prefix
        return from == to;
    }
    

    output:

    'a' <= c && c <= 'b'||'1' <= c && c <= '9'|| c === '_'