1. 模板文件 test04.ftl
foo
<@customUpper>
bar f
<#-- 这里允许使用所有的 FTL -->
<#list [, , ] as color>
${color}
</#list>
baaz
</@customUpper>
wombat
2. 自定义指令类 UpperDirective.java
ps: 一个把字符串变为大写的指令
package com.freemarker.test04.Directives;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
/**
* FreeMarker 的用户自定义指令在逐步改变
* 它嵌套内容的输出转换为大写形式
* <p><b>指令内容</b></p>
* <p>指令参数:无
* <p>循环变量:无
* <p>指令嵌套内容:是
*/
public class UpperDirective implements TemplateDirectiveModel {
public void execute(Environment env,
Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body)
throws TemplateException, IOException {
if (!params.isEmpty()) {
throw new TemplateModelException(
"This directive doesn't allow parameters.");
}
if (loopVars.length != 0) {
throw new TemplateModelException(
"This directive doesn't allow loop variables.");
}
if (body != null) {
body.render(new UpperCaseFilterWriter(env.getOut()));
} else {
throw new RuntimeException("missing body");
}
}
/**
* {@link Writer}改变字符流到大写形式,
* 而且把它发送到另外一个{@link Writer}中。
*/
private static class UpperCaseFilterWriter extends Writer {
private final Writer out;
UpperCaseFilterWriter (Writer out) {
this.out = out;
}
@Override
public void write(char[] cbuf, int off, int len)throws IOException {
char[] transformedCbuf = new char[len];
for (int i = 0; i < len; i++) {
transformedCbuf[i] = Character.toUpperCase(cbuf[i + off]);
}
out.write(transformedCbuf);
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
}
}
}
3. 测试类文件 Test.java
package com.freemarker.test04.Directives;
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File("templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Map root = new HashMap();
root.put("customUpper", new UpperDirective());
Template temp = cfg.getTemplate("test04.ftl");
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
out.close();
}
}
运行结果
foo
BAR F
RED
GREEN
BLUE
BAAZ
wombat