簡體   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