`

freemarker中实现自定义标签(2.3.11版本以前的方式)

阅读更多

扩展你自己的转换器
      转换器接口TemplateTransformModel有一个方法 Writer getWriter(Writer out, Map args)。该方法将会转换标签之间的内容,首先把标签之间的内容读取到 Writer 对象中,再由 Writer对象对其中的内容施行转换处理,转换后的内容会再次存储到Writer 中。调用 flush 方法后会把内容输出。不需要你去调用out.close(),当到达结束标签的时候close 会自动被调用。

以下是转换标签之间内容为大写的例子:

import java.io.*;
import java.util.*;
import freemarker.template.TemplateTransformModel;

public class UpperCaseTransformModel implements TemplateTransformModel {

	public Writer getWriter(Writer out, Map args) {
		return new UpperCaseWriter(out);
	}

	private class UpperCaseWriter extends Writer {
		private Writer out;

		UpperCaseWriter(Writer out) {
			this.out = out;
		}

		public void write(char[] cbuf, int off, int len) throws IOException {
			out.write(new String(cbuf, off, len).toUpperCase());
		}

		public void flush() throws IOException {
			out.flush();
		}

		public void close() {
		}
	}
}

 

 

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

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

/**
 * 
 * 模板工具类
 */
public class FreeMarkertUtil {
	/**
	 * @param templatePath 模板文件存放目录 
	 * @param templateName 模板文件名称 
	 * @param root 数据模型根对象
	 * @param templateEncoding 模板文件的编码方式
	 * @param out 输出流
	 */
	public static void processTemplate(String templatePath, String templateName, String templateEncoding, Map<?,?> root, Writer out){
		try {
			Configuration config=new Configuration();
			File file=new File(templatePath);
			//设置要解析的模板所在的目录,并加载模板文件
			config.setDirectoryForTemplateLoading(file);
			//设置包装器,并将对象包装为数据模型
			config.setObjectWrapper(new DefaultObjectWrapper());
			
			//获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
			Template template=config.getTemplate(templateName,templateEncoding);
			//合并数据模型与模板
			
		    template.process(root, out);
		    out.flush();
		    out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (TemplateException e) {
			e.printStackTrace();
		}
		
	} 
}

  

 

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

/**
 * 
 * 客户端测试模板输入类
 */
public class ClientTest {
	public static void main(String[] args) {
		Map<String,Object> root=new HashMap<String, Object>();
		//root.put("length", new StringLengthMethod());
		root.put("upperCase", new UpperCaseTransformModel());
		FreeMarkertUtil.processTemplate("src/templates","demo01.ftl", "UTF-8", root, new OutputStreamWriter(System.out));		
	}
}

 

 模板文件demo01.ftl如下:

测试转换字母为大写字母:
<@upperCase>
abcdef
</@upperCase>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics