java - 在java代码中模板化多行字符串的简单方法

标签 java templating multilinestring

我经常遇到以下情况:我有很长的多行字符串,必须在其中注入(inject)属性 - 例如像模板之类的东西。但我不想在我的项目中包含完整的模板引擎(例如velocity 或freemarker)。

如何以简单的方式完成此操作:

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 ..."; 

最佳答案

使用 Java 15+:

String title = "Princess";
String name = "Luna";
String community = "Stackoverflow";

String text = """
        Dear %s %s!
        This is a question to %s-Community
        for simple approach how to code with Java multiline Strings?
        """.formatted(title, name, community);

关于java - 在java代码中模板化多行字符串的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21232185/

相关文章:

php - 带有某些 html 标记的 JSON 字符串在解析时失败

java - 将原生 uint8_t(Java 字节)转换为 int

java - 什么是生命周期观察器以及如何正确使用它?

java - 为什么 Java 在我的 return 语句之后跳转

go - 来自动态参数的 Hugo 数据文件

Golang 模板无法正常工作

java - 实现远程代理

php - 将 html 网站转换为简单的 PHP 模板网站

php - 从Mysql中提取Json php MultilineString坐标

postgis - STLineMerge 不会将我的 MULTILINESTRING 放入 LINESTRING