我在application.properties文件中放了一些URL。现在,这些URL需要具有该语言,以便页面以不同语言加载。例如,在我的application.properties文件中,我有一个联系我们链接的属性,如下所示
CONTACT_US_LINK = https://my-domain.com/ {区域设置} /接触我们
在上面的链接中,我需要使用当前的应用程序区域设置,这样如果区域设置是" en",则上面的属性将变为
CONTACT_US_LINK = https://my-domain.com/的 EN /接触我们
如何在属性文件中使用我的语言环境变量?
PS:以上属性将在Thymeleaf中访问,如下所示
<li>
<a th:href="@{${@environment.getProperty('contact_us_link')}}" th:text="#{footer.contactUs.text}">Contact Us</a>
</li>
答案 0 :(得分:2)
对于其他stackoverflow用户,我从Thymeleaf文档中找到了一个解决上述问题的简单解决方案。
在我的 application.properties 文件中,我使用了以下属性
contact_us_link = https://my-domain.com/ {locale} / contact-us
在我的html $ {@ environment.getProperty('contact_us_link')} 中,从应用程序属性文件获取url,此外,我还传递与 {locale} < / strong>,如下所示
<li>
<a th:href="@{${@environment.getProperty('contact_us_link')}(locale=${locale.toLowerCase()})}" th:text="#{footer.contactUs.text}">Contact Us</a>
</li>
我可以使用Thymeleaf模板中的 $ {locale} 变量访问当前语言环境。
下面是官方文档的链接
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#link-urls
答案 1 :(得分:1)
您可能应该使用消息包(application.properties
)来使用国际化(i18n),而不是使用messages.properties
。
如果您使用的语言数量有限,则可以为每种语言创建单独的属性文件,例如:
messages.properties
:默认/后备messages_en.properties
:英文翻译的属性messages_de.properties
:德语翻译的属性如果这些文件中的每一个都包含contact_us_link
属性,Spring将自动解析它们。在您的Thymeleaf模板中,您应该使用以下内容:
<small th:text="#{contact_us_link}"></small>
或者,如果您需要更动态的方法,可以从所有本地化的message_*.properties
文件中删除该属性,并在messages.properties
文件中使用占位符,例如:
contact_us_link=https://my-domain.com/{0}/contact-us
现在,您可以在模板中将区域设置作为替换传递:
<a th:href="#{contact_us_link(locale)}">Contact us</a>
如果您确实需要使用application.properties
,则必须自行进行替换。幸运的是,您可以使用SpEL在模板中提供的所有内容,因此您可以创建自己的bean:
@Component
public class Formatter {
public String format(String message, Object... variables) {
return MessageFormat.format(message, variables);
}
}
现在你可以用这个bean替换它:
<a th:href="${@formatter.format(@environment.getProperty('contact_us_link'), #locale)}">Contact us</a>
答案 2 :(得分:0)
我不认为春天会在获取百里香的财产时提供/翻译地区。相反,您可以为每个区域设置创建不同的密钥并相应地获取它们。
contact_us_link_en = https://my-domain.com/en/contact-us
在获取百里香的财产时使用$ {#locale}。