Simple way templating multiline strings in java code
I'm often run in to the following situation: I have long multiline strings where properties must be injected - e.g. something like templating. But I don't want to inlcude a complete templating engine (like velocity or freemarker) in my projects.
How can this be done in a simple way:
String title = "Princess";
String name = "Luna";
String community = "Stackoverflow";
String text =
"Dear " + title + " " + name + "!\n" +
"This is a question to " + community + "-Community\n" +
"for simple approach how to code with Java multiline Strings?\n" +
"Like this one.\n" +
"But it must be simple approach without using of Template-Engine-Frameworks!\n" +
"\n" +
"Thx for ...";
You can create your own small & simply template engine with few lines of code:
public static void main(String[] args) throws IOException {
String title = "Princes";
String name = "Luna";
String community = "Stackoverflow";
InputStream stream = DemoMailCreater.class.getResourceAsStream("demo.mail");
byte[] buffer = new byte[stream.available()];
stream.read(buffer);
String text = new String(buffer);
text = text.replaceAll("§TITLE§", title);
text = text.replaceAll("§NAME§", name);
text = text.replaceAll("§COMMUNITY§", community);
System.out.println(text);
}
and small text file e.g. in the same folder (package) demo.mail
:
Dear §TITLE§ §NAME§!
This is a question to §COMMUNITY§-Community
for simple approach how to code with Java multiline Strings?
Like this one.
But it must be simple approach without using of Template-Engine-Frameworks!
Thx for ...
One basic way of doing it would be to use String.format(...)
Example:
String title = "Princess";
String name = "Celestia";
String community = "Stackoverflow";
String text = String.format(
"Dear %s %s!%n" +
"This is a question to %s-Community%n" +
"for simple approach how to code with Java multiline Strings?%n" +
"Like this one.%n" +
"But it must be simple approach without using of Template-Engine-Frameworks!%n" +
"%n" +
"Thx for ...", title, name, community);
More info