Frequently I run into this problem. I want to generate a line of text if
the text is not empty. If it is empty, do not generate the line.
Illustration template:
namespace @classSpec.getNamespace()
@classSpec.getComment()
class @classSpec.getName() {
...
}
If @classSpec.getComment() returns meaningful comment text, the result looks like
namespace com.example
// this is comment
class MyClass {
...
}
But if there is no comment, it will be
namespace com.example
class MyClass {
...
}
Notice the extra empty line? I do not want it. Currently the solution is to write template as
namespace @classSpec.getNamespace()
@classSpec.getComment()class @classSpec.getName() {
...
}
and
make sure the getComment() will append a "\n" to the return value. This
makes the template much less readable. Also, imagine I need to generate
a function with multiple parameters in a for loop. If each parameter
requires multiple lines of template code, I need to make them all
written in one line. Otherwise, the result file will have function like
function myFunction(
String stringParam,
Integer intParam,
Long longParam
)
The
core problem is, the template file does not only containe scripts, but
also raw text to be written in the output. For script part, we want
newlines and indentations. We want the space to be trimmed just like
what compilers usually do. But for raw text, we want the spaces to be
exact as specified in the file. I feel we need a bit more raw text
control mechanism to reconcile the two parts.
Specific to this
case, is there some special symbol to treat multiple lines as single
line in the output? For example, like if we can write
namespace @classSpec.getNamespace()
@classSpec.getComment()\\
class @classSpec.getName() {
...
}
Thanks!