在 java class 上声明键时检索键的值
Retrieve value of key when key is declared on java class
我正在使用 spring 网络流 2.5.0
以及 thymeleaf 3.0.9
。
我有一个 class 包含一些静态键例如:
public class MyKeys{
.....
public static final String myKey = "myKey1"
.....
}
为了在模板文件中可用,我在控制器的某处存储了该键的值。
(伪代码):
context.add(MyKeys.mykey,"screen.home.welcome");
screen.home.welcome
是一个 i18n 消息键(存储在应用程序的 message.properties
上),我想将其值呈现给用户。
这有效但是我想使用来自MyKeys
class的键来访问它的值。
<div th:utext="#{${myKey1}}"></div>
我尝试过但 没有 工作:
<div th:utext="#{${T(com.package.MyKeys).myKey}}"></div>
有了这个,我在模板中得到的是myKey1
。我如何指示 thymeleaf 检索与 myKey1
?
关联的值
您想要的间接级别有点奇怪...这不起作用的原因:
<div th:utext="#{${T(com.package.MyKeys).myKey}}"></div>
// Resolves to
<div th:utext="#{myKey1}"></div>
// Which isn't the actual message key since it's supposed to look like this:
<div th:utext="#{screen.home.welcome}"></div>
我可能不会推荐它,但您可以为此使用预处理。像这样的东西可能对你有用:
<div th:utext="#{${__${T(com.package.MyKeys).myKey}__}}"></div>
// Resolves to
<div th:utext="#{${myKey1}}"></div>
// Resolves to
<div th:utext="#{screen.home.welcome}"></div>
这可能也有效:
<div th:utext="#{${#root.get(T(com.package.MyKeys).myKey)}}"></div>
我正在使用 spring 网络流 2.5.0
以及 thymeleaf 3.0.9
。
我有一个 class 包含一些静态键例如:
public class MyKeys{
.....
public static final String myKey = "myKey1"
.....
}
为了在模板文件中可用,我在控制器的某处存储了该键的值。
(伪代码):
context.add(MyKeys.mykey,"screen.home.welcome");
screen.home.welcome
是一个 i18n 消息键(存储在应用程序的 message.properties
上),我想将其值呈现给用户。
这有效但是我想使用来自MyKeys
class的键来访问它的值。
<div th:utext="#{${myKey1}}"></div>
我尝试过但 没有 工作:
<div th:utext="#{${T(com.package.MyKeys).myKey}}"></div>
有了这个,我在模板中得到的是myKey1
。我如何指示 thymeleaf 检索与 myKey1
?
您想要的间接级别有点奇怪...这不起作用的原因:
<div th:utext="#{${T(com.package.MyKeys).myKey}}"></div>
// Resolves to
<div th:utext="#{myKey1}"></div>
// Which isn't the actual message key since it's supposed to look like this:
<div th:utext="#{screen.home.welcome}"></div>
我可能不会推荐它,但您可以为此使用预处理。像这样的东西可能对你有用:
<div th:utext="#{${__${T(com.package.MyKeys).myKey}__}}"></div>
// Resolves to
<div th:utext="#{${myKey1}}"></div>
// Resolves to
<div th:utext="#{screen.home.welcome}"></div>
这可能也有效:
<div th:utext="#{${#root.get(T(com.package.MyKeys).myKey)}}"></div>