5

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?

Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
AKumar
  • 95
  • 2
  • 14
  • 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 Mar 08 '19 at 13:12

2 Answers2

3

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);
  }
}
soorapadman
  • 4,451
  • 7
  • 35
  • 47
1

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

Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51