消息表达式用于从消息源中提取消息内容实现国际化。
表达式的语法:#{...}
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
消息属性可以是传统的静态值
home.welcome=¡Bienvenido a nuestra tienda de comestibles!
也可以带有参数声明,参数声明格式符合java.text.MessageFormat标准
home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!
通过在消息名称后边加括号声明参数的方式#{messageKey(param=value)}实现参数赋值
<p th:utext="#{home.welcome(${session.user.name})}">
Welcome to our grocery store, Sebastian Pepper!
</p>
多个参数用“,”分割
#{messageKey(param1=value1, param2=value2)}
messageKey本身可以是一个变量表达式
<p th:utext="#{${welcomeMsgKey}(${session.user.name})}">
Welcome to our grocery store, Sebastian Pepper!
</p>
#消息源
大多数情况下, 消息源是*.properties文件,同时可以自定义其他消息源,比如数据库。消息源通过org.thymeleaf.messageresolver.IMessageResolver获取,如果在初始化模板引擎时没有自定义的IMessageResolver被提供,那么一个默认的实现org.thymeleaf.messageresolver.StandardMessageResolver*会被自动提供。
StandardMessageResolver查找和模板文件位于同级目录,且具有和模板文件相同名字的*.properties*文件。
模板*/WEB-INF/templates/home.html*在渲染时,会根据local设置,使用下面的消息源文件
- /WEB-INF/templates/home_zh_CN.properties for中文
- /WEB-INF/templates/home_en.properties for英文
- /WEB-INF/templates/home.properties 如果特定的lcoal不可用时使用
本文介绍了Thymeleaf的消息表达式,用于从消息源获取国际化内容。消息属性支持静态值和参数声明,遵循Java.text.MessageFormat标准。消息源通常是.properties文件,Thymeleaf使用IMessageResolver接口,如果没有自定义实现,则使用StandardMessageResolver。在渲染如/WEB-INF/templates/home.html的模板时,StandardMessageResolver会查找与模板同名的.properties文件,根据locale加载对应的语言资源。

298

被折叠的 条评论
为什么被折叠?



