Call a template expression from another in XTend
-
12-12-2019 - |
Question
i have a question about calling template expression methods from another template expression.
The example below didn't work, ie. it doesn't expand and 'prints' the code on the spot it was called. How can I modify this code to print the result of ResourceGenerator().generate(resource)
on the spot where it is called? Note that ResourceGenerator().generate(resource)
is in itself a template expression.
class ServerGenerator extends RESTServiceGenerator {
def generate(Server it) '''
package nl.sytematic.projects.RESTServiceServlet;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("«it.baseURI»")
public class «it.name» {
«it.resources.forEach[ resource |new ResourceGenerator().generate(resource)]»
}
'''
}
Hope I am clear in my question. An example would be great! (Again: ResourceGenerator().generate returns a CharSequence).
Solution
forEach always returns null and is just about doing side-effects. What you want is a map and a join.
it.resources.map(resource |new ResourceGenerator().generate(resource)).join
But there's an even better way:
«FOR resource : resources»
«new ResourceGenerator().generate(resource)»
«ENDFOR»
I suggest to hold and reuse a single instance of ResourceGenerator as a field (do you use dependency injection?) or make ResourceGenerator::generate static.