velocity: join optional fields with a separator/prefix

Posted by SlowStrider on Stack Overflow See other posts from Stack Overflow or by SlowStrider
Published on 2013-10-18T09:52:30Z Indexed on 2013/10/18 9:53 UTC
Read the original article Hit count: 226

Filed under:
|
|
|
|

What would be the most concise/readable way in a velocity template to join multiple fields with a separator while leaving out empty or null Strings without adding excess separators?

As an example we have a tooltip or appointments that goes like:

Appointment ($number) [with $employee] [-] [$remarks] [-] [$roomToVisit]

Where I used brackets to indicate optional data. When filled in it would normally show as

Appointment (3) with John - ballroom - serve Java coffee

When $remarks is empty but $roomToVisit is not, this becomes:

Appointment (3) with John - ballroom

When $remarks is "serve Java coffee" but $roomToVisit is empty we get:

Appointment (3) with John - serve Java coffee

When both are empty:

Appointment (3) with John

Bonus: also make the field prefix optional. When only $employee is empty we should get:

Appointment (2) serve Java coffee - ballroom

Ideally I would like the velocity template to look very similar to the first code box. If this is not possible, how would you achieve this with a minimum of distracting code tags?

Similar ideas (first is much more verbose):

© Stack Overflow or respective owner

Related posts about java

Related posts about templates