2008-12-17 33 views
1

有沒有辦法將Velocity配置爲使用toString()之外的其他方法將對象轉換爲模板中的字符串?例如,假設我使用format()方法使用簡單的日期類,並且每次都使用相同的格式。如果所有的我速度的代碼如下所示:配置速度以使用toString之外的其他東西渲染對象?

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

有一些配置,我可以添加將我只想說

$someDate 

呢? (假設我不能編輯日期類並給它一個合適的toString())。

我在使用WebWork構建的Web應用程序的上下文中執行此操作(如果有幫助的話)。

回答

1

你也可以創建自己的ReferenceInsertionEventHand它會監視您的日期並自動爲您設置格式。

1

速度允許同樣的工具,叫做Velocimacros的一個JSTL:

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

這將允許你定義一個宏,如:

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

然後調用它像這樣:

#d($someDate) 
+0

,這也固定它作爲默認格式。無需將其傳遞到任何地方。確實是一個更好的主意。 – 2008-12-18 03:55:39

1

哦,1.6+版本的Velocity有一個新的Renderable接口。如果你不介意將日期類綁定到Velocity API,那麼實現這個接口,Velocity將使用render(context,writer)方法(對於你的情況,你只是忽略上下文並使用writer)而不是toString( )。

0

我也遇到了這個問題,我能夠根據Nathan Bubna answer解決它。

我只是想完成答案,提供link to Velocity documentation,它解釋瞭如何使用EventHandlers。

在我的情況下,每次插入引用時,我都需要Velocity對來自gson庫的所有JsonPrimitive對象調用「getAsString」而不是toString方法。

這是爲創建

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; 
    } 

} 

簡單且事件​​添加到VelocityContext

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

... 

context.attachEventCartridge(vec); 
相關問題