This tutorial is about #foreach loop in velocity.
Velocity has #foreach element for looping. Please find below template for more details.
Please click this link for Velocity Dependency & Introduction.
1 2 3 4 5 |
Example of foreach in velocity. #foreach($site in $sites) Site Name : $site #end |
Loop starts with #foreach
and ends with #end
Note :
#foreach
can only accept javajava.lang.Iterable
implementation. Like List, Set etc
Find below code example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.omt.velocity.example; 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.Velocity; public class LoopInVelocity { public LoopInVelocity() { } public static void main(String args[]) { List<String> sites = new ArrayList<>(); sites.add("omtlab.com"); sites.add("google.com"); sites.add("facebook.com"); sites.add("apple.com"); loopInVelocity(sites); } private static void loopInVelocity(List<String> sites) { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("sites", sites); Template t = Velocity.getTemplate("loop.vm"); StringWriter sw = new StringWriter(); t.merge(context, sw); System.out.println(sw.toString()); } } |
Output :
1 2 3 4 5 6 |
Example of foreach in velocity. Site Name : omtlab.com Site Name : google.com Site Name : facebook.com Site Name : apple.com |