tags:

views:

1094

answers:

1

What is the best way to create Velocity Template from a String?

I'm aware of Velocity.evaluate method where I can pass String or StringReader, but I'm curios is there a better way to do it (e.g. any advantage of creating an instance of Template).

+4  A: 

There is some overhead parsing template. You might see some performance gain by pre-parsing the template if your template is large and you use it repeatedly. You can do something like this,

        RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();            
        StringReader reader = new StringReader(bufferForYourTemplate);
        SimpleNode node = runtimeServices.parse(reader, "Template name"));
        Template template = new Template();
        template.setRuntimeServices(runtimeServices);
        template.setData(node);
        template.initDocument();

Then you can call template.merge() over and over again without parsing it everytime.

BTW, you can pass String directly to Velocity.evaluate().

ZZ Coder
Exactly what I was looking for. Thanks.For other people's reference, runtimeServices is an instance of org.apache.velocity.runtime.RuntimeInstance
tomsame
Missed one-line. For completeness, I added it.
ZZ Coder