Freemarker格式化缩进文本,处理include指令与import指令

在使用include指令时,文本会顶格到最左边,没有缩进。

这篇文章使用了自定义指令处理内容缩进
http://yuanhuiwu.iteye.com/blog/1133067

本文使用了不同的实现方式(一个一个翻API,费了半天劲总算找到了)



/** * 增加缩进的格式化指令,由标签起始位置决定输出多少空格 * 例如: * <@format> * <#include path="..." /> * </@format> * */ public class FormatDirective implements TemplateDirectiveModel { @Override public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { FormatWriter writer = new FormatWriter(env.getOut(), env.getCurrentDirectiveCallPlace().getBeginColumn()); body.render(writer); } private static class FormatWriter extends Writer { private Writer out; private char[] space; public FormatWriter(Writer out, int column) { this.out = out; this.space = new char[column]; Arrays.fill(this.space, ' '); } @Override public void write(char[] cbuf, int off, int len) throws IOException { out.write(space); out.write(cbuf); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } } }

猜你喜欢

转载自www.cnblogs.com/dreamycloud/p/9148887.html