使用 # 从 thymeleaf 消息表达式中获取值并进行空检查

Fetch value from thymeleaf message expression using # and doing null check

我正在使用 # 从 XML 模板中获取值。但是当我为不可用的标签获取值时。我将其 属性 名称作为标签名称。 如果该标签在 xml 文件中不可用,我想设置一个默认值。

<th:block th:replace="fragments/header :: nav-header-back-text(header_txt=
 #{label.btn.unsubscribe+'_'+${operator_id}} ?  
#{label.btn.unsubscribe+'_'+${operator_id}} : #{label.btn.unsubscribe})">

假设 operator_id 是 com,那么我想要 如果 label.btn.unsubscribe_com 可用则显示它,否则显示消息资源中 label.btn.unsubscribe 的值,但我得到类似 ??label.btn.unsubscribe+'_'+${operator_id} 的信息??.

我正在使用 thymeleaf 和 spring 引导,上面的代码写在 html 文件中。

您不能像在 #{...} 表达式中那样构建字符串。相反,您需要使用 #messages 助手。这样的事情应该有效。我没有设置你所有的消息,但像这样的东西应该可以工作:

<th:block th:replace="fragments/header :: nav-header-back-text(header_txt=${#messages.msgOrNull('label.btn.unsubscribe_' + operator_id)} ?: #{label.btn.unsubscribe})">