1

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 - serve Java coffee - ballroom

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

Appointment (3) with John - ballroom

When instead $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 (3) 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 (velocity example may help but is much more verbose):

Community
  • 1
  • 1
Henno Vermeulen
  • 1,495
  • 2
  • 15
  • 25
  • - Suggestions for other template engine that can do this are welcome - Note that I now achieve similar functionality in Java code with helper methods like "joinNonEmpty" and "prefixIfNotEmpty – Henno Vermeulen Oct 18 '13 at 09:59

1 Answers1

0

I found out that you can invoke your own Java methods by registering a Java class as a tool in the context. An existing example is the DisplayTool. I create a VelocityStringUtil class with the methods "pre" and vararg method "join" for conditional prefix and join, and registered it as:

context.put("text", new VelocityStringUtil());

Using this, the following template creates the expected output:

Appointment ($number)$text.pre(' ', $text.join(' - ', $text.pre('with ', $employee), $remarks, $roomToVisit))

As you can see it's still a bit ugly, but I think it's better than using predefined directives (unless I am missing something).

Henno Vermeulen
  • 1,495
  • 2
  • 15
  • 25