如何创建动态模板字符串

时间:2010-03-03 04:35:02

标签: java spring templates

是否有任何API使用Spring或java替换模板字符串以及值。

例如:

Dear %FIRST_NAME% %LAST_NAME%,
---- remaining text-----------

其中参数(FIRST_NAMELAST_NAME)的格式为Map

4 个答案:

答案 0 :(得分:2)

编写执行此操作的代码相对简单。如果您要做很​​多事情,那么您可能希望使用现有的库Velocity。但是它对值使用不同的语法。请参阅Getting Started

如果您想自己写这个,请尝试:

public static String replaceAll(String text, Map<String, String> params) {
  return replaceAll(text, params, '%', '%');
}

public static String replaceAll(String text, Map<String, String> params,
    char leading, char trailing) {
  String pattern = "";
  if (leading != 0) {
    pattern += leading;
  }
  pattern += "(\\w+)";
  if (trailing != 0) {
    pattern += trailing;
  }
  Pattern p = Pattern.compile(pattern);
  Matcher m = p.matcher(text);
  boolean result = m.find();
  if (result) {
    StringBuffer sb = new StringBuffer();
    do {
      String replacement = params.get(m.group(1));
      if (replacement == null) {
        replacement = m.group();
      }
      m.appendReplacement(sb, replacement);
      result = m.find();
    } while (result);
    m.appendTail(sb);
    return sb.toString();
  }
  return text;
}

例如:

String in = "Hi %FIRST_NAME% %LAST_NAME%.";
Map<String, String> params = new HashMap<String, String>();
params.put("FIRST_NAME", "John");
params.put("LAST_NAME", "Smith");
String out = replaceAll(in, params);
System.out.println(out);

输出:

Hi John Smith.

答案 1 :(得分:0)

答案 2 :(得分:0)

我最喜欢的模板引擎是Apache Velocity

与Spring完美整合,还有一篇介绍性文章here

答案 3 :(得分:0)

用法:

replaceAll(string,
        "param1", "value 1",
        "param12", "value 12");

实现:

public static String replaceAll(String text, Object... replacements) {
    Assert.isTrue(replacements.length % 2 == 0, "Is not key - value pairs: " + replacements);

    Map< String, String> longToShortNamesMap = new TreeMap<>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.length() == o2.length() ? o1.compareTo(o2) : o2.length() - o1.length();
        }
    });
    for (int i = 0; i < replacements.length; i += 2) {
        longToShortNamesMap.put(Objects.toString(replacements[i]), Objects.toString(replacements[i+1]));
    }
    String result = text;
    for (String key : longToShortNamesMap.keySet()) {
        Assert.isTrue(text.contains(key), "Can not find key in the text " + key);
        result = result.replaceAll(key, longToShortNamesMap.get(key));
    }
    return result;
}