Simple java lib for text templating? [closed]
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this questionI need to template some email texts. Nothing fancy, just replace something like @name@
with real value. No pictures, no fancy formatting etc.
What java lib could you recommend? The simplier the better.开发者_StackOverflow
A library-free alternative to the libraries already suggested: java.text.MessageFormat
.
StringTemplate is another option. The five-minute introduction gives some basic examples and syntax.
StringTemplate hello = new StringTemplate("Hello, $name$",
DefaultTemplateLexer.class);
hello.setAttribute("name", "World");
System.out.println(hello.toString());
You can give Velocity or Freemarker a shot. I've used both in email templating engines. They provide simple syntax for basic use cases, but you can get pretty complex later on!
Of the two, I personally prefer Freemarker because they've done a really good job of providing all sorts of different builtins that make formatting numbers and text very simple.
Have you tried Apache Velocity?
Try Apache Velocity or FreeMarker, they can be helpful, for me I am using FreeMarker
It very simple to do it yourself:
public class Substitution {
public static void main(String[] args) throws Exception {
String a = "aaaa@bbb@ccc";
// This can be easiliy FileReader or any Reader
Reader sr = new StringReader(a);
// This can be any Writer (ie FileWriter)
Writer wr = new StringWriter();
for (;;) {
int c = sr.read();
if (c == -1) { //EOF
break;
}
if (c == '@') {
String var = readVariable(sr);
String val = getValue(var);
wr.append(val);
}
else {
wr.write(c);
}
}
}
/**
* This finds the value from Map, or somewhere
*/
private static String getValue(String var) {
return null;
}
private static String readVariable(Reader sr)throws Exception {
StringBuilder nameSB = new StringBuilder();
for (;;) {
int c = sr.read();
if (c == -1) {
throw new IllegalStateException("premature EOF.");
}
if (c == '@') {
break;
}
nameSB.append((char)c);
}
return nameSB.toString();
}
}
You have to polish it a little bit, but that's all.
Agreed, Apache's Velocity is a good call for embedded situations.
If you want a stand-alone product, you can also use Apache's Ant. It reduces the template within a copy task by applying substitution filters.
精彩评论