views:

231

answers:

3

Is there a way to configure Velocity to use something other than toString() to convert an object to a string in a template? For example, suppose I'm using a simple date class with a format() method, and I use the same format every time. If all of my velocity code looks like this:

$someDate.format('M-D-yyyy')

is there some configuration I could add that would let me just say

$someDate

instead? (Assuming I'm not in a position to just edit the date class and give it an appropriate toString()).

I'm doing this in the context of a webapp built with WebWork, if that helps.

+1  A: 

Velocity allows for a JSTL like utility called velocimacros:

http://velocity.apache.org/engine/devel/user-guide.html#Velocimacros

This would allow you to define a macro like:

#macro( d $date)
   $date.format('M-D-yyyy')
#end

And then call it like so:

#d($someDate)
Mike
And this also fixed it as a Default format. No need to pass it everywhere. A better idea, indeed.
Adeel Ansari
+1  A: 

You could also create your own ReferenceInsertionEventHandler that watches for your dates and automatically does the formatting for you.

Nathan Bubna
+1  A: 

Oh, and the 1.6+ versions of Velocity have a new Renderable interface. If you don't mind tying your date class to a Velocity API, then implement this interface and Velocity will use the render(context, writer) method (for your case, you just ignore the context and use the writer) instead of toString().

Nathan Bubna