How can I trim whitespace by Velocity

I just read this article on Velocity Whitespace Gobbling which suggests a few work-arounds including Velocity Whitespace Truncated By Line Comment.

This basically suggests commenting out line breaks by putting comments at the end of each line. It also suggests not indenting the code in your macros to prevent superfluous (one of my favourite words) spaces occurring.

TBH it's not a great solution but may suit your needs. Simply put ## at the end of each line in your macro and that will make things a little bit nicer... sort of


Solution

In the class where you create the VelocityEngine, add a method as follows

public String trim(String str) {
    return str.trim()/*.replace("\n", "").replace("\r", "")*/;
}

then add the following to the VelocityContext that you create:

    context.put("trimmer", this);

and finally in the velocity template do the following

<a href="#">$trimmer.trim("#render_something('xxx')")</a>

Why does it work?

Although the behavior of Velocity is clearly define, it can be a bit tricky to see how it works sometimes. The separate trim()-method is necessary to get the char-sequence from the template into a Java method where you can call the actual trim() on the String. As far as I know there is no trim inside Velocity, but you always can call back to Java with tricks like this one.

The double-quotes are necessary because the #render_something is just a macro, not a function call, this means the results of the statements in the macro are put verbatim into the point where the macro is "executed".


It seems just java native trim() works.

$someValue.trim() works for me