File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Struts and the fly likes How to handle arrays in Velocity? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "How to handle arrays in Velocity?" Watch "How to handle arrays in Velocity?" New topic
Author

How to handle arrays in Velocity?

Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
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?


Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

There isn't currently.

http://marc.theaimsgroup.com/?l=velocity-user&m=106699466205257&w=2
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4462
    
    6

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.


Junilu - [How to Ask Questions] [How to Answer Questions]
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
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

Joined: Jan 23, 2002
Posts: 11962
    
    5
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

Joined: Jan 23, 2002
Posts: 11962
    
    5
Ok. It works. Thanks, Junilu!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to handle arrays in Velocity?