Arithmetic Expressions in VTL using #set
#set method is used to evaluate the expressions in VTL.
Example
#set ($c = $a + $b)
|
import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class ExpressionInVTLExample {
public static void main(String args[]){
VelocityEngine ve = new VelocityEngine();
ve.init();
Template t = ve.getTemplate("velocitytemplate.vm");
VelocityContext vc = new VelocityContext();
vc.put("a", 30);
vc.put("b", 20);
StringWriter sw = new StringWriter();
t.merge(vc, sw);
System.out.println(sw);
}
}
|
Velocitytemplate.vm
Arithmetic Expressions in VTL
A = $a
B = $b
#set ($sum = $a + $b)
Sum = $sum
#set ($min = $a - $b)
Minus = $min
#set ($mul = $a * $b)
Multiply = $mul
#set ($div = $a / $b)
Division = $div
#set ($mod = $a % $b)
Modules = $mod
|
Output
Arithmetic Expressions in VTL
A = 30
B = 20
Sum = 50
Minus = 10
Multiply = 600
Division = 1
Modules = 10
|