| 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();
		root.put("thing", thing);
		Template template=config.getTemplate("missing.ftl");
		StringWriter out=new StringWriter();
		template.process(root, out);

	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}

age: ${thing.age}


age: 30