Iterate Map Velocity Template

Iterate Map Velocity Template

Iterate map object in velocity template is same as we iterate map in java. To make it more clear I will create List and put map inside it and iterate in template using small project:

  • Maven project structure:

Iterate Map 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>
  • SampleRenderMap.vm
<HTML>
<BODY>
<table border="1" style="width:20%">
#foreach( $data in $bar )
	#foreach( $mapEntry in $data.entrySet() )
      <tr>
        <td>
          Key: $mapEntry.key
        </td>
        <td>
          Value: $mapEntry.value
        </td>
      </tr>
     #end
#end
</table>
  • IterateMapVelocityTemplate.java:
package com.javahonk;

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

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

public class IterateMapVelocityTemplate {

	public static void main(String[] args) {
		
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		Template t = ve.getTemplate("./src/main/resources/templates/SampleRenderMap.vm");
		VelocityContext vc = new VelocityContext();
		List<Map<String, Object>> bar = new ArrayList<Map<String, Object>>();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("Test", "Value1");
		data.put("Tes2", "Value2");
		bar.add(data);
		vc.put("bar", bar);
		StringWriter sw = new StringWriter();
		t.merge(vc, sw);
		System.out.println(sw);
	}

}
  • Output:

Iterate Map 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 *