• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to handle arrays in Velocity?

 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recently played around with the Velocity template language available in the Roller Weblogger software powering blogging sites such as JRoller.com and was disappointed to realize that I wasn't able to access the elements of an array in anyway other than using a foreach loop.
This is what the documentation suggests:

However, this approach fails because the object returned by the get() method is of type String[]. So, I needed a way of getting the first element of the array. I couldn't figure out what would do it. I tried square brackets, get(0), and what not.
This is what I got working:

I wonder... Is there a better way? There has to be, right?
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There isn't currently.

http://marc.theaimsgroup.com/?l=velocity-user&m=106699466205257&w=2
 
Junilu Lacar
Bartender
Pie
Posts: 7747
60
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Took a quick look at the documentation you linked to and the only thing I can think of to suggest is to refactor a bit and "extract to a macro" the logic for displaying the first element.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mike. I actually searched the Velocity mailing list (again, this time with more patience) and found this message confirming my fears... I also noticed that RC1 for Velocity 1.4 is out, but decided not to read the change log as the JRoller.com site is not going to upgrade in a while anyway.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Junilu Lacar:
Took a quick look at the documentation you linked to and the only thing I can think of to suggest is to refactor a bit and "extract to a macro" the logic for displaying the first element.

Umm. I didn't think of that. I'll go and test it right away.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. It works. Thanks, Junilu!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic