2012-08-22 19 views
1

我想在獨立應用程序中使用VelocityTool的GenericTools進行一些標準格式化。例如在我的Velocity模板像這樣使用GenericTools' NumberTool格式:在獨立應用程序中使用Velocity的GenericTools的更好方法?

Total: $numberTool.format("#0.00", $totalPnL) 

我如何上面的‘$ numberTool’與GenericTool NumberTool關聯。這裏是我的速度編碼:

Velocity.init(); 
VelocityContext velocityContext = new VelocityContext(); 
Template template = Velocity.getTemplate("example.vm"); 
velocityContext.put("totalPnL", 100); 
StringWriter sw = new StringWriter(); 
template.merge(velocityContext, sw); 

現在我知道我能做到這一點,以得到它的工作:

velocityContext.put("numberTool", new NumberTool()); 

不過是,我需要怎麼所有的GenericTools添加到我的應用程序?手動和一次一個(例如DateTool的另一行...等)?沒有辦法讓所有的GenericTools都暴露給我的模板嗎?我知道VelocityTools附帶的「tools.xml」具有GenericTools定義的功能。我可以將它添加到我的應用程序以公開所有工具嗎?如果是這樣,怎麼樣?

感謝, 大衛

+0

除非你有一個非常有說服力的理由來使用Velocity單例,否則建議使用VelocityEngine實例。 –

回答

1

它至少我做到這一點的方式。 我會把例如

context.put("esc", new EscapeTool()); 

,並在模板中,我只是用那麼

${esc.h} 

在代碼中寫一個「#」,這樣的速度不解析爲「速度腳本」。

我認爲這些輔助工具相當實用,只涵蓋一些基本的標誌。他們不打算成爲一個標準,你可以按需要包括他們。

我已經構建了一個抽象類,它加載速度的上下文並將EscapeTool始終放入上下文中,以便我不必將它添加到任何地方。

與項目

塞巴斯蒂安