Search code examples
javaloopsxtextxtendxpand

Xtend/Xpand find and replace (rule)


Is it possible set a rule that will allow an Xpand method to output a specified string of text depending on the input. For example:

«FOR a:e.attributes»
 Type = «a.eClass.name»
 Value = «a.name.toFirstUpper»

«ENDFOR»

The above code may output:

Type = StringAttribute
Value = String1

Type = IntegerAttribute
Value = 123

How would I make this output:

Type = String
Value = String1

Type = int
Value = 123

I know this can be done with if statements but I would like to be able it to be more or less automatic. It would be a waste to have to specify such rules every time I need to output these details in the same file. Could someone show me what kind of code I could use to achieve this? Thank you.


Solution

  • I suggest that you create a reusable Xtend helper

    toSimpleName(String inp):
        switch (inp) {
            case "StringAttribute"  : "String"
            case "IntegerAttribute" : "int"
            // ...more cases here...
            default                 : inp
        }
    ;
    

    and then call it from your Xpand template like this:

    «FOR a:e.attributes»
     Type = «a.eClass.name.toSimpleName()»
     Value = «a.name.toFirstUpper»
    
    «ENDFOR»