Skip to content

4.7 文本拼接(+ 运算符)

无论文本是字面量、变量表达式结果,还是消息表达式结果,都可以通过 + 运算符轻松拼接。

html
<span th:text="'The name of the user is ' + ${user.name}">
  The name of the user is Guest
</span>
核心逻辑解释
  1. 拼接规则+ 运算符会按顺序拼接左右两侧的内容:

    • 左侧是文本字面量 'The name of the user is '(注意末尾的空格);
    • 右侧是变量表达式 ${user.name}(假设值为 John);
    • 最终拼接结果为 The name of the user is John,替换 <span> 内的默认文本。
  2. 多段拼接支持: 可同时拼接多个文本/表达式,顺序执行:

    html
    <!-- 拼接 文本 + 变量 + 文本,结果如 "John (ID: 1001)" -->
    <span th:text="${user.name} + ' (ID: ' + ${user.id} + ')'">
      Guest (ID: 0)
    </span>
  3. 与消息表达式拼接: 也可结合 #{...} 消息表达式拼接,实现多语言文本+动态变量的组合:

    html
    <!-- 假设 home.greeting=¡Hola!,最终结果如 "¡Hola! John" -->
    <span th:text="#{home.greeting} + ' ' + ${user.name}">
      Hello Guest
    </span>
关键注意事项
  • 空格处理:拼接时需注意文本中的空格,避免出现“连字”问题: ❌ 错误:'The name of the user is' + ${user.name}(结果为 The name of the user isJohn,缺少空格); ✅ 正确:'The name of the user is ' + ${user.name}(文本末尾加空格)。
  • 空值处理:若变量为 null,拼接后会显示字符串 "null",需提前判断或用默认值运算符:
    html
    <!-- 优化:user.name 为 null 时显示 "Anonymous" -->
    <span th:text="'The name of the user is ' + (${user.name} ?: 'Anonymous')">
      The name of the user is Guest
    </span>
  • 简化写法(字面量替换): 对于“文本+变量”的简单拼接,Thymeleaf 还提供了更简洁的字面量替换语法(|...|),等价于 + 拼接但更易读:
    html
    <!-- 等价于 'The name of the user is ' + ${user.name} -->
    <span th:text="|The name of the user is ${user.name}|">
      The name of the user is Guest
    </span>

总结

  1. + 运算符是 Thymeleaf 中拼接文本的基础方式,支持文本字面量、变量表达式、消息表达式的任意组合拼接;
  2. 拼接时需注意空格和空值问题,避免出现格式错误或 "null" 字符串;
  3. 简单的“文本+变量”拼接推荐使用 |...| 字面量替换语法,代码更简洁易读。