Search code examples
xtend

Xtend: add indentation to template


I want to create a template that's indented 4 spaces, like below:

def myMethod() '''
        for (int i =0; i!= size; ++i) {
            doSomething();
        }
    '''

But Xtend removes the 4 spaces before the for() and the closing '}'. How can I add indentation that's not removed?


Solution

  • I have had similar issues, Xtend's template system can be finicky, but there are workarounds. When using something like the method you showed I usually find I call it from another part of the template and you can create the indentation in the calling method. For instance:

    def callingMethod() {'''
        for (1 to 10) {
            «myMethod()»  «««   This puts indents before everything within the method
        }
    '''}
    def myMethod() {'''
        for (int i =0; i!= size; ++i) {
            doSomething();
        }
    '''}
    

    Another option is to explicitly add whitespace within the template such as:

    def myMethod() {'''
        «"    "»for (int i =0; i!= size; ++i) {
        «"    "»    doSomething();
        «"    "»}
    '''}
    

    Or another way I found looking just now

    def myMethod() {'''
    «""»
        for (int i =0; i!= size; ++i) {
            doSomething();
        }
    «""»
    '''}
    

    Personally I think it is much cleaner the first way where possible. There are probably other ways to achieve this as well, these are just a few things I have found in my own work.