如何在Thymeleaf的th:text中判断多变量空值并实现多语言动态展示
解决方案
你可以通过Thymeleaf内置的字符串判断工具+国际化消息工具实现这个需求,有两种实现方式可选:
方案1:直接在Thymeleaf模板中实现
首先建议你先将国际化消息的key修改为语义化命名,方便后续维护:
# 国际化properties文件 date.start=Starts on(en), Débute le (fr) date.end=Ends on( en), se termine le (fr) time.start=begins to (en), commence à(fr) time.end=finishes at (en), se termine à (fr)
然后替换你的th:text写法:
th:text="${#strings.trim( (not #strings.isEmpty(item?.startDate) and not #strings.isEmpty(item?.endDate)) ? (#messages.msg('date.start') + ' ' + item.startDate + ' ' + #messages.msg('date.end') + ' ' + item.endDate + ' ') : '' + (not #strings.isEmpty(item?.startTime) and not #strings.isEmpty(item?.endTime)) ? (#messages.msg('time.start') + ' ' + item.startTime + ' ' + #messages.msg('time.end') + ' ' + item.endTime) : '' )}"
实现说明
- 用
#strings.isEmpty()判断变量是否为空,兼容null和空字符串两种场景,避免页面出现null字样 - 用
#messages.msg()读取国际化配置,自动适配当前语言环境 - 外层用
#strings.trim()去除两端多余的空格,避免出现空内容导致的留白问题 - 完全匹配你要求的三种展示规则:
- 仅日期非空时只展示日期段内容
- 仅时间非空时只展示时间段内容
- 四个变量都非空时自动拼接两部分内容
方案2:后端预处理(更推荐)
如果不想把过多逻辑写在模板里,可以直接在Item实体类中新增计算属性,在后端处理好拼接逻辑:
// Item实体类新增方法 public String getScheduleDesc(Locale locale) { StringBuilder sb = new StringBuilder(); MessageSource messageSource = SpringContextUtil.getBean(MessageSource.class); // 拼接日期部分 if (!StringUtils.isEmpty(this.startDate) && !StringUtils.isEmpty(this.endDate)) { sb.append(messageSource.getMessage("date.start", null, locale)) .append(" ").append(this.startDate) .append(" ").append(messageSource.getMessage("date.end", null, locale)) .append(" ").append(this.endDate).append(" "); } // 拼接时间部分 if (!StringUtils.isEmpty(this.startTime) && !StringUtils.isEmpty(this.endTime)) { sb.append(messageSource.getMessage("time.start", null, locale)) .append(" ").append(this.startTime) .append(" ").append(messageSource.getMessage("time.end", null, locale)) .append(" ").append(this.endTime); } return sb.toString().trim(); }
模板里直接调用即可:
th:text="${item.getScheduleDesc(#locale)}"
这种方式逻辑更清晰,也方便做单元测试,后续调整规则只需要修改后端代码即可。
内容的提问来源于stack exchange,提问作者Camel4488
相关产品推荐
相关产品推荐

