Thymeleaf消息表达式

来源:互联网 发布:王者荣耀淘宝充值 编辑:程序博客网 时间:2024/09/21 08:16

消息表达式用于从消息源中提取消息内容实现国际化。

表达式的语法:#{...}

<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不可用时使用
0 0
原创粉丝点击