Tiny是非常优秀的模板引擎templateengine,但网络上相关文档又少,官方文档有缺陷,今天研究下tiny模板函数的自定义方法。在使用tiny模引擎板时,除了可以使用tiny预制的函数(例如formatDate、random、now),还可以自定义函数,以下是自定义一个replace函数Demo的步骤。
一、定义模板函数
定义一个函数,实现字符串的替换。该函数可定义多个名称,功能相同。
import org.tinygroup.template.Template;
import org.tinygroup.template.TemplateContext;
import org.tinygroup.template.TemplateException;
import org.tinygroup.template.function.AbstractTemplateFunction;
public class StringReplaceFunction extends AbstractTemplateFunction {
public StringReplaceFunction() {
super("replace,replaceAll");
}
public Object execute(Template template, TemplateContext context, Object... parameters) throws TemplateException {
if (parameters != null && parameters.length >= 3 && parameters[0] != null) {
return parameters[0].toString().replaceAll(parameters[1].toString(), parameters[2].toString());
} else {
throw new TemplateException("replace函数必须输入转换的参数");
}
}
}
二、注册模板函数
在spring容器初始化时,注册新的模板函数。
@Autowired
private TemplateEngine engine;
@PostConstruct
private void init(){
engine.addTemplateFunction(new StringReplaceFunction());
}
三、使用模板函数
${replace('账号已注销,不允许做利息分配', '注销', '解约')}
此外,还有另一种方法可以使用自定义方法
一、引入maven坐标
<dependency>
<groupId>org.tinygroup</groupId>
<artifactId>org.tinygroup.templateengine</artifactId>
<version>3.4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.tinygroup</groupId>
<artifactId>org.tinygroup.context</artifactId>
<version>3.4.11</version>
<scope>test</scope>
</dependency>
二、定义模板函数
@Component
public class NetUtils{
public String getIP() {
String ip = "127.0.0.1";
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
}
三、设置上下文参数
TemplateContext templateContext = new TemplateContextDefault();
templateContext.put("invoke", netUtils);
四、使用模板函数
${invoke.getIP()}