| Refresh | Home EGTry.com

simple wrapper to simplify the usage of freemarker


assume that template files could be in any package directory.

the usage example

package egtry.freemarker.custom;

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

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


public class FreemarkerSimple extends HashMap<String, Object> {

	
	private static Configuration config;
	static {
		config=new Configuration();
		config.setClassForTemplateLoading(FreemarkerSimple.class, "/");
		config.setObjectWrapper(new DefaultObjectWrapper());
	}
	
	public static void main(String[] args) throws Exception {
		FreemarkerSimple context=new FreemarkerSimple();
		context.put("name", "John Carter");
		System.out.println(context.render("/egtry/freemarker/custom/custom.ftl"));
		System.out.println(context.render(FreemarkerSimple.class, "custom.ftl"));
	}
	
	public String render(Class relativeToClass, String templateName) throws IOException, TemplateException {
		String className=relativeToClass.getName();//assume that we hava a package
		String packageName=className.substring(0, className.lastIndexOf('.'));
		String absoluteTemplateName="/"+packageName.replace('.', '/')+"/"+templateName;
		return render(absoluteTemplateName);
	}
	
	public String render(String templateName) throws IOException, TemplateException {
		StringWriter out=new StringWriter();
		Template template=config.getTemplate(templateName);
		template.process(this,out);
		return out.getBuffer().toString();
	}

}


template

A simple template
name: ${name}


Output

A simple template
name: John Carter


A simple template
name: John Carter