import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;
public class VelocityExp {
public static void main(String[] args) throws Exception {
Velocity.init();
Template t = Velocity.getTemplate("./src/test/VelocityExp.html");
VelocityContext ctx = new VelocityContext();
Set
Demov d1 = new Demov();
d1.setName("one");
d1.setAge("24");
d1.setKe(new demo2("one"));
Demov d2 = new Demov();
d2.setName("two");
d2.setAge("23");
d2.setKe(new demo2("two"));
Demov d3 = new Demov();
d3.setName("true");
d3.setAge("22");
d3.setKe(new demo2("three"));
Demov d4 = new Demov();
d4.setName("ofour");
d4.setAge("21");
d4.setKe(new demo2("four"));
names.add(d1);
names.add(d2);
names.add(d3);
names.add(d4);
ctx.put("products",names);
ctx.put("date", new DateTool());
ctx.put("dbdate",new Date());
ctx.put("rowCount",new Integer(1));
Writer writer = new StringWriter();
t.merge(ctx, writer);
System.out.println(writer);
}
}
Html file content:
<html>
<head>
<title>velocity test</title>
</head>
<body>
<table>
#foreach($product in $products)
#if ($rowCount % 2 == 0)
#set ($bgcolor = "#0000FF")
Applying BLUE color here
#else
Applying RED color here
#set ($bgcolor = "#FF0000")
#end
<tr>
<td bgcolor="$bgcolor">$product.name</td>
<td bgcolor="$bgcolor">$product.age</td>
<td bgcolor="$bgcolor">$product.ke.k</td>
</tr>
#set ($rowCount = $rowCount + 1)
#end
</table>
Displaying how to use date format here:
$dbdate
$date.get('medium')
$date.format('medium',$dbdate)
</body>
</html>