例如,我有:
String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}."
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");
期望输出:"Hi Bob, you have successfully ordered a sofa."
获得所需输出的最佳(万无一失、可维护、省时等(方法是什么?
我想做一些简单的事情:
String output = templateString;
for (Map.Entry<String, String> entry : parameters.entrySet()) {
output = output.replace("{{" + entry.getKey() + "}}", entry.getValue());
}
有没有更好的方法?
取决于您需要的模板系统有多复杂。已经有很多了。
两个例子是:
- 字符串模板
- 速度
另一种方法是使用Mustache.java
, docs
String templateString = "Hi {{customerName}}, you have successfully ordered a {{itemName}}.";
Map<String, String> parameters = new HashMap<>();
parameters.put("customerName", "Bob");
parameters.put("itemName", "sofa");
Writer writer = new StringWriter();
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(new StringReader(templateString), "example");
mustache.execute(writer, parameters);
writer.flush();
System.out.println(writer.toString());
最好使用Map中的键获取值
String output = templateString;
output = output.replace("{{customerName}}",parameters.get("customerName"));
output = output.replace("{{itemName}}",parameters.get("itemName"));
除了其他答案中已经提供的解决方案外,您还可以使用Apache Commons Text中的StringSubstitutor
。
https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html 的一个例子:-
Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumps over the ${target}.";
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);