2017-01-22 65 views
1

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

代码示例:

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替换为其值?感谢您的帮助。

谢谢。

回答

1

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

所以你必须预先处理模板,喜欢的东西:

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

非常感谢克劳德。这个解决方案为我工作。 我只需要知道在内容变大时这是否会有任何性能相关问题,并且需要知道这种方式是否违反任何编码标准。 –

+0

是的,显然有性能方面的问题,并且它肯定有点骇人听闻...... –