word-tpl采用SPI的方式进行方法的扩展,同样也支持手动扩展
标签或者语法的扩展
该类库采用SPI的方式自动加载扩展函数,你也可以手动注册扩展函数。
1.编写函数
public class WordRunFunction implements WordTplFunction {
@Override
public String getName() {
//扩展函数的方法名称
return "wordRun";
}
@Override
public void invoke(WordTpEnvironment environment, Map param, WordTplFunctionBody body) {
//environment 环境变量,包含模板引擎的变量,运行环境的变量,
// param 执行方法的参数
// body 表示代码块的内容区域,如果是单行函数,则为null
Object index = param.get("index");
if (index != null){
environment.setCurrentIndex(WordTpEnvironment.CURRENT_RUN_TAG,index);
}
try {
if (body != null){
String exec = body.exec();
//获取当前代码所在的word run对象。
XWPFRun currentRun = environment.getCurrentRun();
if (!WordParse.checkHaveTag(exec)){
currentRun.setText(exec,0);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
2.注册函数
- 采用方法注册
FreemarkerWordTplFactory tplFactory = new FreemarkerWordTplFactory();
tplFactory.registerFunction(new WordRunFunction());
- 采用SPI注册
在jar包中新建文件 /META-INF/services/com.github.xuejike.wordtpl.tpl.WordTplFunction
文件内容填写需要扩展的类全路径
com.github.xuejike.wordtpl.tpl.functions.WordRunFunction
3.使用函数
由于我采用的是Freemarker模板引擎,那么使用方法就是使用freemarker自定义指令的方式。
<@wordRun index ="1">sssss</@wordRun>