4
votes

I have a java String which is basically a velocity template.

String vt = "#foreach ($number in [1..34])  $number += $number  #end"
String result = *String_vt_calculated_by_Velocity_Engine*;
System.out.println(result);

How can I evaluate the above String in Java and get the result?

2
You've already stated that it is a Velocity template, so feed that string to Velocity and get the result back. How to do that should be coveredy by the Velocity documentation. - Thomas

2 Answers

2
votes

You have to use Velocity.Evaluate check this Document

import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
public class LoadTemplateFromStringTest {

  public static void main(String[] args)  {
       VelocityContext context = new VelocityContext();

       StringWriter sw = new StringWriter();
      String vt = "#foreach ($number in [1..34])  $number += $number  #end";
        Velocity.evaluate( context, sw, "", vt);
        System.out.println(sw);
  }
}
1
votes

You can pass it to Velocity.evaluate() (see org.apache.velocity.app.Velocity in the API).