2

I'm looking for a nice template engine or short piece of code to expand Ant-like variables in a string in Java. Example:

String result = expand ("${firstName} ${familyName}", map);

It should at least support java.util.Map but something that can handle beans or recursive lookups or lookups in a list of maps/objects would be welcome, too.

Suggestions?

[EDIT] In reply to TofuBeer: No nesting, only valid Java identifiers within the {}. Anything outside of ${} should be copied verbatim. $$ should become $``. If that's not possible ${dollar} should expand to a single $ (so you can express 15.00 $).

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • Can $, { or } appear inside a ${....}? Will the string to expand have each ${....} separated by whitespace? Will the string to expand have characters other than whitespace and ${....}? – TofuBeer Dec 09 '09 at 10:14
  • @TofuBeer: No nesting, only valid Java identifiers within the {}. Anything outside of ${} should be copied verbatim. $$ should become $. If that's not possible ${dollar} should expand to a single "$". – Aaron Digulla Dec 09 '09 at 13:18

3 Answers3

5

StrSubstitutor from Commons Lang does pretty much what you're asking for

MonkeyWrench
  • 1,809
  • 2
  • 24
  • 48
Valentin Rocher
  • 11,667
  • 45
  • 59
1

use StringTemplate in order to implement expand:

void expand(String template, Map<String,String> map) {
    StringTemplate st = new StringTemplate(template);

    for (Map.Entry<String, String> attribute : map) {
       st.setAttribute(attribute.getKey(), attribute.getValue());
    }

    return st.toString();
} 
dfa
  • 114,442
  • 31
  • 189
  • 228
  • Yes, StringTemplate is a very good and simple engine yet flexible. I was about to post this answer when I clicked the question... Greetz, GHad – GHad Dec 09 '09 at 10:29
0

Have a look at Freemarker och Velocity, both of them are template engines

Kennet
  • 5,736
  • 2
  • 25
  • 24