我是 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");
...
关于java - 使用 Velocity Template 将索引替换为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41793932/