SpringBoot中Velocity动态模版引擎

1,037 阅读1分钟

Velocity简介

Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。当Velocity 应用于web开发时,界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人员可以只关注页面的显示效果,而由java程序开发人员关注业务逻辑编码。

Velocity使用场景

Java工程中Mybatis逆向工程的生成,相关邮件模版、钉钉模版的动态渲染等场景都可适用。

Velocity基础语法

1."#"用来标识Velocity的关键字,包括#set、#if 、#else、#end、#foreach、#end、#include、#parse、#macro等;

2."$"用来标识Velocity的变量;如:$i、$msg、$TagUtil.options(...)等。

3."{}"用来明确标识Velocity变量;比如在页面中,页面中有一个$someonename,此时,Velocity将把someonename作为变量名,若我们程序是想在someone这个变量的后面紧接着显示name字符,则上面的标签应该改成${someone}name。

4."!"用来强制把不存在的变量显示为空白。如:当找不到username的时候,$username返回字符串"$username",而$!username返回空字符串""

Velocity动态赋值

       <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.6</version>
        </dependency>
@Component
public class VelocityUtil {

    @Resource
    private VelocityEngine velocityEngine;

    public String velocityMergeContent(Map<String, Object> initData, String templateContent) {
        try {
            StringWriter writer = new StringWriter();
            VelocityContext context = new VelocityContext();

            if (MapUtils.isNotEmpty(initData)) {
                initData.entrySet().forEach(entry -> context.put(entry.getKey(), entry.getValue()));
            }

            velocityEngine.evaluate(context, writer, "dingDing", templateContent);

            return writer.toString();
        } catch (IOException e) {
            return null;
        }
    }
}

这里的initData是动参map集合,其key与模版中的动参name保持一一对应