【问题标题】:thymeleaf internationalization use default text htmlthymeleaf 国际化使用默认文本 html
【发布时间】:2016-05-09 00:54:54
【问题描述】:

我在 Spring Boot 中使用 thymeleaf,

<span th:text="#{home.welcome}">Welcome Default Message</span>

当在messages.properties中找不到key时,我有

??home.welcome_en_US??

我不想翻译messages.properties 中的每条消息。当找不到翻译关键消息时,我希望在 html 页面中写入“欢迎默认消息”。

我该怎么做?

【问题讨论】:

  • 然后将其添加到您的messages.properties 中,该文件中的值基本上是默认值。 message_yourLanguage.properties 包含已翻译的内容。
  • 其实我并不想创建默认messages.properties,我想在thymeleaf html模板中使用默认message。
  • 你不能因为它们总是被替换,这就是百里香叶的工作原理。也许在自定义方言中有一个解决方案,您可以在其中指定表达式中的默认值。

标签: spring internationalization spring-boot thymeleaf


【解决方案1】:

也许不再相关,但以下内容对我有用。我正在运行 Thymeleaf 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

【讨论】:

    【解决方案2】:

    仅在存在翻译的情况下有条件地显示元素

    <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>
    

    如果您想显示默认文本,这不是最优雅的解决方案。

    看看 thymeleaf documentation 上的#messages 实用方法。

    也许你会找到更优雅的解决方案。但是,我的示例仍然可以解决您的问题。

    【讨论】:

    • 这是第一个线索,可能我必须创建自己的 th:properties 才能做到这一点。
    【解决方案3】:

    使用Elvis operator in Spring

    <span th:text="${#messages.msgOrNull('home.welcome')?:'Welcome Default Message'}"></span>
    

    【讨论】:

      猜你喜欢
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      相关资源
      最近更新 更多