繁体   English   中英

使用 VelocityTemplate 用值替换索引

[英]Replace indexes with values using VelocityTemplate

我是 Java Velocity Templates 的新手。 我有一个字符串,它将包含一些数字占位符/变量。 我需要用相应的值替换它们。 我怎么能在java中实现这一点?

代码示例:

String templateString = "Replacing $0 with its value.";
VelocityContext context = new VelocityContext();
context.put("0", "Sample value");

StringWriter output = new StringWriter();
Velocity.evaluate(context, output, "log or null", templateString);

System.out.println("output: " + output);

上面的代码没有用“示例值”替换 $0 变量,但是当我有一个字符串作为占位符/变量而不是 $0 时它起作用了。 是否有任何解决方法可以将 $0 替换为其值? 感谢您在这方面的帮助。

谢谢。

Velocity 本身没有解决方法:解析器不允许引用名称以数字开头。

因此,您必须对模板进行预处理,例如:

templateString = templateString.replaceAll("\\$(\\d+)","\\$_$1");
context.put("_0", "Sample value");
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM