编写自定义标签需要实现 freemarker.template.TemplateDirectiveModel 接口
demo如下
freemarker模板 freemarker自定义标签.ftl
<#assign x = 1>
<@repeat count=4>
Test ${x}
<#assign x = x + 1>
</@repeat>
<@repeat count=3; cnt>
${cnt}. Test
</@repeat>
TemplateDirectiveModel 接口的实现类
package com.yydb.lp.freemarker.customlabel;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import freemarker.core.Environment;
import freemarker.template.SimpleNumber;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
public class RepeatDirective implements TemplateDirectiveModel {
/**
* @param environment
* @param map
* <@repeat count=3;
* cnt>其中count=3就以键值对的形式存在map中,只是3不是java类型,而是TemplateModel类型
* (整数:TemplateNumberModel
* ,字符串:TemplateScalarModel,boolean:TemplateBooleanModel 等),
* 所以利用map.getValue(......)返回的是一个TemplateModel类型的数据,需转换成int类型数据。
* @param atemplatemodel
* 变量,如cnt,atemplatemodel是一个TemplateModel类型的数组,我们可以在程序中给它赋值
* @param templatedirectivebody
*/
@Override
public void execute(Environment environment, Map map, TemplateModel atemplatemodel[], TemplateDirectiveBody templatedirectivebody) {
Writer out = null;
try {
if (templatedirectivebody == null) {// 自定义标签必须有内容,即自定义 开始标签与结束标签之间必须有 内容
throw new TemplateModelException("null body");
} else {
out = environment.getOut();
// TemplateNumberModel 数字类型, TemplateScalarModel 字符串类型,
// TemplateBooleanModel boolean类型
TemplateNumberModel numberModel = (TemplateNumberModel) map.get("count");
int count = numberModel.getAsNumber().intValue();
for (int i = 0; i < count; i++) {
if (atemplatemodel.length > 0) {
atemplatemodel[0] = new SimpleNumber(i + 1);
}
templatedirectivebody.render(out);
}
}
} catch (TemplateModelException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
测试代码
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public static void main(String[] aegs) throws IOException, TemplateException {
Configuration configuration = new Configuration();
configuration.clearTemplateCache();
configuration.setTemplateLoader(new FileTemplateLoader(new File("D:/")));
Template template = configuration.getTemplate("/freemarker自定义标签.ftl",Locale.CHINA,"UTF-8");
Map<String,Object> rootMap = new HashMap<String,Object>();
//以下两行代码功能是一样的,这里我们使用第二行代码
// configuration.setSharedVariable("repeat", new RepeatDirective());
rootMap.put("repeat", new RepeatDirective());
StringWriter sw = new StringWriter();
template.process(rootMap, sw);
System.out.println(sw.toString());
}