Templateengine自定义Tiny模板函数的两种方法

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()}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值