0
votes

I'm quite new to Velocity templates, and try to get a phone number of 8 digits displayed like "12 34 56 78" or "123 45 678".

I've tried a lot of variations, including

  1. $number.format('00 00 00 00',${phone})
  2. $number.format('#0 00 00 00',$phone)
  3. $display.printf("%s %s %s %s", $phone.substring(0,2), $phone.substring(2,4), $phone.substring(4,6), $phone.substring(6,8))

Where $number = new NumberTool() and $display = new DisplayTool()

The two first outputs the number without spaces, while the last one is not parsed by Velocity.

2

2 Answers

2
votes

Method three will work. What's wrong is that $phone is a number in your code and substring() will work on strings. It is probably printing "null" in your code when the template is resolved.

The simple fix is to convert $phone to a string. Just do something like:

#set ($phoneString = $phone.toString())
$display.printf("%s %s %s %s", $phoneString.substring(0,2), $phoneString.substring(2,4), $phoneString.substring(4,6), $phoneString.substring(6,8))

and you'll be good to go.

For anybody looking for a US-style phone format try:

$displayTool.printf("(%s) %s-%s", $phoneString.substring(0,3), $phoneString.substring(3,6), $phoneString.substring(6,10))
0
votes

I ended up for now with a separate class to do the formatting via MessageFormat and putting that on the context:

$phoneNumber.format($phone)

I guess there must be an easier way to do it directly inside the template?