我经常遇到以下情况:我有很长的多行字符串,其中必须注入属性 - 例如像模板一样的东西。但我不想在我的项目中包含一个完整的模板引擎(如速度或自由标记)。
如何以简单的方式完成:
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 ...";
答案 0 :(得分:3)
你可以创建自己的小&只需几行代码的模板引擎:
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);
}
和小文本文件,例如在同一文件夹(包)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 ...
答案 1 :(得分:1)
这样做的一个基本方法是使用String.format(...)
示例:
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);
答案 2 :(得分:1)
答案 3 :(得分:0)
您可以使用String#format()
:
String title = "Princess";
String name = "Luna";
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);
答案 4 :(得分:0)
Java没有内置的模板支持。您的选择是:
您可以使用String.format(...)
,MessageFormat
等类似地更简洁地编写上述代码,但它们不会让您走得太远...除非您的模板非常简单。
相比之下,有些语言内置支持字符串插值,“此处”文档或简洁的结构构建语法,可以适应模板。
答案 5 :(得分:0)
您可以使用java.text.MessageFormat
:
String[] args = {"Princess, "Luna", "Stackoverflow"};
String text = MessageFormat.format("Bla bla, {1}, and {2} and {3}", args);