You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证Velocity模板是否完成所有变量替换?(Velocity 1.7)

如何在Velocity 1.7中验证模板变量是否全部替换

核心结论

Velocity 1.7本身没有原生支持在模板存在未替换变量时自动抛出错误的功能,但可以通过自定义上下文或后处理校验的方式实现需求。

实现方案

方案1:自定义StrictVelocityContext拦截未定义变量

创建自定义上下文类,重写变量获取逻辑,当访问未定义的变量时直接抛出异常:

import org.apache.velocity.VelocityContext;

public class StrictVelocityContext extends VelocityContext {
    @Override
    public Object get(String key) {
        Object value = super.get(key);
        if (value == null) {
            throw new IllegalArgumentException("模板中存在未定义的变量:" + key);
        }
        return value;
    }
}

替换原代码中的VelocityContext为自定义类即可:

VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();

Template t = velocityEngine.getTemplate("card.vm");

StrictVelocityContext context = new StrictVelocityContext();
context.put("firstName", "tuk");
StringWriter writer = new StringWriter();
try {
    t.merge(context, writer);
} catch (IllegalArgumentException e) {
    // 捕获并处理未定义变量异常
    System.err.println(e.getMessage());
}

方案2:后处理输出内容检查未替换变量

如果不想修改上下文逻辑,可以在模板合并完成后,检查输出文本中是否残留${变量名}格式的未替换片段:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 原模板合并代码不变
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();

Template t = velocityEngine.getTemplate("card.vm");

VelocityContext context = new VelocityContext();
context.put("firstName", "tuk");
StringWriter writer = new StringWriter();
t.merge(context, writer);

// 检查未替换变量
String output = writer.toString();
Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");
Matcher matcher = pattern.matcher(output);
if (matcher.find()) {
    throw new IllegalArgumentException("模板中存在未替换的变量:" + matcher.group(1));
}

注意事项

  • 方案1局限性:若模板中使用了变量默认值语法(如${lastName:默认值}),super.get()会返回默认值,不会触发异常,需根据需求调整逻辑。
  • 方案2局限性:若输出内容本身包含${xxx}格式的合法文本(非模板变量),会导致误判,需结合模板实际场景调整正则规则。

内容的提问来源于stack exchange,提问作者tuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 19:37:05