| Refresh | Home EGTry.com

conditional display if a value is defined and initialized


if a value is not defined, or defined but not initialized, freemarker throws an exception for using it.

define the values in the java

package egtry.freemarker.datatype;

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 MissingValue {


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

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

		
		Map<String, Object> root=new HashMap<String, Object>();
		Thing thing=new Thing();
		//thing.setName("Name1");
		thing.setAge(30);
		root.put("thing", thing);
		Template template=config.getTemplate("missing.ftl");
		
		
		StringWriter out=new StringWriter();
		
		template.process(root, out);
		
		System.out.println(out.getBuffer().toString());

	}
	
	
	public static class Thing {
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
		private String name;
		private int age;
		
		
	}

}


freemarker template

<#if thing.name??>
this line is optional. name: ${thing.name}
</#if>

age: ${thing.age}



Output

age: 30