【问题标题】:Spring Boot (1.4.1) and Thymeleaf (3) MessageSource single quotesSpring Boot (1.4.1) 和 Thymeleaf (3) MessageSource 单引号
【发布时间】:2017-03-07 18:41:58
【问题描述】:

我对 Spring Boot (1.4.1) 和 Thymeleaf (3) 中的 MessageSource 消息有疑问。

文件 app.properties

app.quotes=Francesco's title
app.quotes2=Francesco''s title

当我打印消息时在 page.html 中

<h2 th:text="#{app.quotes}"></h2>
<h2 th:utext="#{app.quotes}"></h2>
<h2 th:text="#{app.quotes2}"></h2>
<h2 th:utext="#{app.quotes2}"></h2>

我明白了(th:text 或 th:utext 没有任何区别)

  • 弗朗西斯科的头衔
  • 弗朗西斯科的头衔
  • 弗朗西斯科的头衔
  • 弗朗西斯科的头衔

在我的控制器中

private final Logger log = LoggerFactory.getLogger(this.getClass());    

@Autowired
private MessageSource messages;

@RequestMapping(value="/page", method = RequestMethod.GET)
public String page() {

    String text = messages.getMessage("app.quotes", null, LocaleContextHolder.getLocale());
    String text2 = messages.getMessage("app.quotes2", null, LocaleContextHolder.getLocale());

    log.debug("text = " + text);
    log.debug("text2 = " + text2);

    // Output
    return "page";
}

我记录的文本是

  • text = Francescos title
  • text2 = Francesco's title

这是可以预测的,因为属性消息中的单引号必须用双单引号转义(“Francesco's title”应该是正确的文本)。 如何让 Thymeleaf 像 MessageSource 那样打印转义双单引号的消息,或者 MessageSource 像 Thymeleaf 那样返回纯文本? 我不想根据调用者使用不同的键/值。

提前感谢您的帮助。

【问题讨论】:

    标签: spring spring-boot properties internationalization thymeleaf


    【解决方案1】:

    只要消息不包含参数 (app.quote=John's message),Spring 就不会解析消息,但如果有参数 (app.quote={0}'s message) 就会这样做

    您可以使用setAlwaysUseMessageFormat 覆盖此行为:

    @Bean
    MessageSource defaultMessageSource(){
     org.springframework.context.support.ReloadableResourceBundleMessageSource source = new org.springframework.context.support.ReloadableResourceBundleMessageSource();
    source.setAlwaysUseMessageFormat(true);
    return source;
    }
    

    也可以看看resolveCodeWithoutArguments

    【讨论】:

    • 感谢您的回答。我已经设置了属性 spring.messages.always-use-message-format=true 并且现在 thymeleaf 可以正确打印所有带有双单引号的文本。
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2018-03-21
    • 2021-09-03
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2016-02-05
    • 2017-06-11
    相关资源
    最近更新 更多