Adjust speed to render object with something other than toString?

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

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

      

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

$someDate

      

instead of this? (Assuming I'm not able to just edit the date class and assign toString () to it).

I am doing this in the context of a webapp created with WebWork, if that helps.

+1


source to share


4 answers


You can also create your own ReferenceInsertionEventHandler that keeps track of your dates and automatically does the formatting for you.



+1


source


Velocity lets you use a JSTL utility called speedimacros:

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

This will allow you to define the macro as:



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

      

And then call it like this:

#d($someDate)

      

+1


source


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

+1


source


I ran into this problem too and I was able to solve it based on Nathan Bubna's answer .

I am just trying to follow through on the answer by providing a link for the Velocity documentation that explains how to use EventHandlers.

In my case, I need Velocity to call "getAsString" instead of the toString method on all JsonPrimitive objects from the gson library every time a link was inserted.

It was as easy as creating

public class JsonPrimitiveReferenceInsertionEventHandler implements ReferenceInsertionEventHandler{

    /* (non-Javadoc)
     * @see org.apache.velocity.app.event.ReferenceInsertionEventHandler#referenceInsert(java.lang.String, java.lang.Object)
     */
    @Override
    public Object referenceInsert(String reference, Object value) {
        if (value != null && value instanceof JsonPrimitive){
            return ((JsonPrimitive)value).getAsString();
        }
        return value;
    }

}

      

And add event to VelocityContext

vec = new EventCartridge();
vec.addEventHandler(new JsonPrimitiveReferenceInsertionEventHandler());

...

context.attachEventCartridge(vec);

      

0


source







All Articles