Better way to use Velocity's GenericTools in a Standalone app?

狂风中的少年 提交于 2019-12-09 23:27:14

问题


I want to use VelocityTool's GenericTools for some standard formatting in a standalone app. e.g. have something like this in my Velocity template to use the GenericTools' NumberTool formatter:

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

How do I associate the above "$numberTool" with the GenericTool NumberTool. Here's my Velocity code:

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

Now I know I can do this to get it to work:

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

But is that how I need to add all the GenericTools to my app? Manually and one at a time (e.g. another line for DateTool ... etc)? Isn't there a way to make all the GenericTools exposed to my template with out this? I know there's a "tools.xml" that comes with VelocityTools that has the GenericTools defined. Can I just add that to my app to expose all the tools? If so, how?

thanks, David


回答1:


http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/ToolManager.html

http://velocity.apache.org/tools/devel/standalone.html

The default tool configuration provides all the generic tools already. Though you can create a config if you want to configure those tools. There's even auto loading for configurations, or manual specification.

   ToolManager tm = new ToolManager();
   tm.setVelocityEngine(yourVelocityEngine);
   Context context = tm.createContext();



回答2:


it is at least the way I do it too. I'll put for example

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

and in the template I simply use then

${esc.h}

to write a "#" in the code so that Velocity does not parse it as "velocity-script".

I think those helper tools are rather utils and only cover some basic signs. They are not intend to be a standard, you rather can include them on-demand.

I've build for example an abstract class that loads the context of velocity and puts the EscapeTool into the context all the time so that I do not have to add it everywhere.

Good luck with your project

Sebastian



来源:https://stackoverflow.com/questions/12080299/better-way-to-use-velocitys-generictools-in-a-standalone-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!