我正在使用带有Spring Boot的百里香叶,
<span th:text="#{home.welcome}">Welcome Default Message</span>
当在消息属性中找不到键时,我有
??home.welcome_en_US??
我不想翻译消息属性中的每条消息。当找不到翻译关键消息时,我希望在 html 页面中写入"欢迎默认消息"。
我该怎么做?
也许不再相关,但以下内容对我有用。我正在运行百里香叶3.0.7.RELEASE。
<span th:text="${#strings.defaultString(#messages.msgOrNull('home.welcome'),'Welcome Default Message')}"/>
如果未找到消息,则 null 将传递给 #strings.defaultString 调用,当给定 null 参数时,该调用将返回"欢迎默认消息"。
更多内容请点击此处 http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#strings
仅在存在翻译的情况下有条件地显示元素
<p th:if="${#messages.msgOrNull('not.so.important.message')}" th:text="#{not.so.important.message}"></p>
http://lukasgrygar.com/thymeleaf/thymeleaf-tips-and-tricks/
在您的情况下,这可以用作:
<span>
<th:block th:if="${#messages.msgOrNull('not.so.important.message')}" th:text="#{not.so.important.message}" />
<th:block th:unless="${#messages.msgOrNull('not.so.important.message')}">Welcome Default Message</th:block>
</span>
如果要显示该默认文本,这不是您最优雅的解决方案。
在百里香叶文档中查看 #messages 实用方法。
也许你会找到更优雅的解决方案。但是,我的例子仍然解决了你的问题。
在 Spring 中使用 Elvis 运算符:
<span th:text="${#messages.msgOrNull('home.welcome')?:'Welcome Default Message'}"></span>