Iterate List Velocity Template

Iterate List Velocity Template

To iterate list object using Apache velocity template first you should load the template and create/put list object in it. I will show this with small project:

  • Final maven project structure:

Iterate List Velocity Template

  • pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javahonk</groupId>
	<artifactId>SendEmailVelocityTemplate</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SendEmailVelocityTemplate Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
			<version>1.7</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SendEmailVelocityTemplate</finalName>
	</build>
</project>
  • SampleRenderList.vm
<HTML>
<BODY>
$velocity!
<table border="1" style="width:20%">
#foreach( $foo in $bar )
      <tr>
        <td>
          $foo
        </td>
      </tr>  
#end
</table>
  • IterateListVelocityTemplate.java
package com.javahonk;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class IterateListVelocityTemplate {

	public static void main(String[] args) {
		
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		Template t = ve.getTemplate("./src/main/resources/templates/SampleRenderList.vm");
		VelocityContext vc = new VelocityContext();
		vc.put("velocity", "Iterate List Velocity template");
		List<String> bar = new ArrayList<String>();
		bar.add("Test");
		bar.add("Test");		
		vc.put("bar", bar);
		StringWriter sw = new StringWriter();
		t.merge(vc, sw);
		System.out.println(sw);
	}

}
  • Output:

Iterate List Velocity Template

  • For more details on Apache Velocity please read it official tutorial here

download Download project: SendEmailVelocityTemplate

Leave a Reply

Your email address will not be published. Required fields are marked *