javavelocity

How to use String as Velocity Template?


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).


Solution

  • There is some overhead parsing the 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);
    Template template = new Template();
    template.setRuntimeServices(runtimeServices);
    
    /*
     * The following line works for Velocity version up to 1.7
     * For version 2, replace "Template name" with the variable, template
     * template.setName("template name");
     * template.setData(runtimeServices.parse(reader, template));
     */
    template.setData(runtimeServices.parse(reader, "Template name"));
    
    template.initDocument();
    

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

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