Java 如何在 Spring 3 / Thymeleaf 中显示带有参数的本地化消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20789441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:21:00  来源:igfitidea点击:

How to show localization messages with parameters in Spring 3 / Thymeleaf

javaspringthymeleaf

提问by Hoffmann

I'm using Spring 3 and Thymeleaf to make some webpages and I am lost as for how to show messages like this:

我正在使用 Spring 3 和 Thymeleaf 制作一些网页,但我不知道如何显示这样的消息:

welcome.message=Hello {0}, welcome!

Welcome.message=你好{0},欢迎!

and then replace {0} with the user name inside thymeleaf tags:

然后将 {0} 替换为 thymeleaf 标签内的用户名:

<h1 th:text="#{welcome.message}">Welcome Placeholder</h1>

I'm not even sure if {0} is the right syntax for the bundle message.

我什至不确定 {0} 是否是捆绑消息的正确语法。

采纳答案by Sotirios Delimanolis

You can use

您可以使用

#{welcome.message(${some.attribute})}

where some.attributewould be the value to use when replacing {0}.

some.attribute替换 时要使用的值在哪里{0}

You should be able to comma separate the values between the ()to add more values to be used.

您应该能够用逗号分隔 之间的值()以添加更多要使用的值。

回答by Serge Tahé

You can even use a calculated message key as a parameter:

您甚至可以使用计算出的消息键作为参数:

<p th:text="#{messages.msg1(${param1})}"></p>
<p th:text="#{messages.msg2(${param2},${param3})}"></p>
<p th:text="#{messages.msg3(#{${param4}})}"></p>

Above, the parameter of [msg3] is a message key [#{key}] where key is itself calculated [${param4}]. The benefit is that you can insert internationalized calculated fragments in an internationalized message.

上面,[msg3]的参数是一个消息键[#{key}],其中key是自己计算出来的[${param4}]。好处是您可以在国际化消息中插入国际化计算片段。

回答by Brett Y

If you need to pass an array of parameters where you don't know the size of the array then you can use:

如果需要在不知道数组大小的情况下传递参数数组,则可以使用:

<p th:text="${#messages.msgWithParams(messageKey, messageParams)}"></p>