|
8:02:22 AM |
|
Why Velocity Does It That Way. Jeff Duska wrote a rant on Velocity:
This let talk about a rant of mine with Velocity. From my work with Velocity, it was acting like the it was a bad reference. The default feature of Velocity is to show the Velocity script when the object your are using is null/invalid in the current context. I think it should think never show the end-user my code, I would expect nothing to display or something like the word Error!!! to display.
If Velocity worked that way then every $ which should be printed would have to be escaped. I think that Velocity is doing it the right way. Right now you just have to start your references with $! instead of $ and bang it won't show up if there is no object for that reference.
[All Things Java]
Velocity Tip
You can override the behaviour of how values are displayed on the page by creating a ReferenceInsertionEventHandler and attaching it to an EventCartridge which is then bound to your Velocity Context.
I use this a lot so the default behaviour for $blah is the same as $!blah (one less char for my lazy brain to remember). This enables something else also... you can allow all $blah values to automatically have their HTML entities escaped without having to think about it - nice eh?
Here's how I override this in WebWorkVelocityServlet:
public class HTMLWebWorkVelocityServlet extends WebWorkVelocityServlet { protected Context createContext( HttpServletRequest request, HttpServletResponse response ) { Context ctx = super.createContext( request, response ); // setup event handler to escape values as they are inserted into page. EventCartridge cartridge = new EventCartridge(); cartridge.addEventHandler( new ReferenceInsertionEventHandler() { public Object referenceInsert( final String reference, final Object value ) { if ( value == null || value.toString().length() == 0 ) { // if no value, return empty string instead of null. return ""; } else { // if value present, escape HTML unfriendly chars. return TextUtils.htmlEncode( value.toString() ); } } } ); cartridge.attachToContext( ctx ); return ctx; } }
(For a quick way to encode HTML chars, see TextUtils.htmlEncode() in OSCore).
|