简体   繁体   中英

Replace indexes with values using VelocityTemplate

I'm a newbee to java Velocity Templates. I'm having a String that will be having some numeric placeholders/variables. I need to replace them with its corresponding values. How could I achieve this in java?

Code sample:

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);

Above code didn't replace the $0 variable with " Sample value ", but it worked when I had a string as the placeholder/variable instead of $0. Are there any workarounds to replace the $0 with its value? Appreciate your help on this.

Thanks.

There is no workaround in Velocity itself: the parser doesn't allow reference names to start with numbers.

So you'll have to pre-process the templates, with something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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