天天看點

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()}