| Refresh | Home EGTry.com

loop statement in the freemarker template - list


java code to set up model

package egtry.freemarker;

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

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class Loop {


	public static void main(String[] args) throws Exception {

		Configuration config=new Configuration();
		config.setClassForTemplateLoading(Loop.class, "");
		config.setObjectWrapper(new DefaultObjectWrapper());
		
		

		
		Map<String, Object> root=new HashMap<String, Object>();
		root.put("week", new String[]{"Mon","Tue","Wed", "Thu", "Fri", "Sat","Sun"});
		Template template=config.getTemplate("loop.ftl");
		
		
		StringWriter out=new StringWriter();
		
		template.process(root, out);
		
		System.out.println(out.getBuffer().toString());

	}

}


template loop.ftl

list each day of a week
<#list week as day>
${day}
</#list>

list each day of a week with a sequence number

<#list week as day>

 <#if day_index % 2 == 0>
  even ${day_index} ${day}
 <#else>
  odd ${day_index} ${day}
 </#if>
 
</#list>


Output

list each day of a week
Mon
Tue
Wed
Thu
Fri
Sat
Sun

list each day of a week with a sequence number


  even 0 Mon
 

  odd 1 Tue
 

  even 2 Wed
 

  odd 3 Thu
 

  even 4 Fri
 

  odd 5 Sat
 

  even 6 Sun