如何使用SpEL处理Thymeleaf中的本地化消息

Mar*_*erg 11 java spring localization spring-el thymeleaf

我是ThymeLeaf的初学者,并且除了@PreAuthorize注释之外没有太多使用SpEL ,所以请非常友好地帮助我.

我正在使用ThymeLeaf(版本2.1.2)和Spring(4.0.2.RELEASE),thymeleaf-spring4并且(据我所知)它用SpEL替换了默认的OGNL脚本.

我想要实现的只是本地化的字符串通过#strings.capitalize函数大写.这是我到目前为止尝试的内容:

<h1 th:text="#{retrievable.key}">Text to be replaced</h1>
Run Code Online (Sandbox Code Playgroud)

完美地工作并给出预期的结果.

现在,当我尝试这个:

<h1 th:text="${#strings.capitalize(#{retrievable.key})}">Text to be replaced</h1>
Run Code Online (Sandbox Code Playgroud)

我得到以下异常(根本原因,为清楚起见省略了):

org.springframework.expression.spel.SpelParseException:
EL1043E:(pos 21): Unexpected token.  Expected 'identifier' but was 'lcurly({)'
Run Code Online (Sandbox Code Playgroud)

好的.只是为了好玩,我省略了大括号并获得了我所期望的:它<h1>是空的.

所以现在我认为可能需要对消息的检索进行预处理,retrievable.key以便在评估时 #strings.capitalize对其进行评估.虽然这对我来说似乎违反直觉和不合逻辑,因为这会破坏所有编程规则,我尝试了这种方法.它也不起作用:使用

${#strings.capitalize(__#retrievable.key__)}
Run Code Online (Sandbox Code Playgroud)

导致

org.thymeleaf.exceptions.TemplateProcessingException:
Could not parse as expression: "#retrievable.key"
Run Code Online (Sandbox Code Playgroud)

和使用

${#strings.capitalize(__#{retrievable.key}__)}
Run Code Online (Sandbox Code Playgroud)

导致(你猜对了)<h1></h1>.

我知道实际问题可以通过CSS或JavaScript解决,但它不一定是关于大写或大写,而是处理本地化字符串,这是一个例子.

那我在这里错过了什么?

Thymeleaf论坛提供的解决方案

ThymeLeaf论坛的Zemi提供了以下优雅的解决方案:

<h1 th:text="${#strings.capitalize('__#{retrievable.key}__')}">Text to be replaced</h1>
Run Code Online (Sandbox Code Playgroud)

请注意单引号.预处理似乎真的意味着在Thymeleaf中进行预处理.

不过,我接受了第一个工作答案.

geo*_*and 10

以下对我有用

<body th:with="message=#{retrievable.key}">
    <h1 th:text="${#strings.capitalize(message)}">Text to be replaced</h1>
</body>
Run Code Online (Sandbox Code Playgroud)