Thymeleaf: 连接-无法解析为表达式

在尝试连接模板中的多个值时,遇到了一个问题。 根据 Thymeleaf 给你,我应该可以简单地把它们放在一起..。

4.6连接文本

文本,无论它们是文本还是计算变量或消息的结果 表达式,可以很容易地连接使用 + 运算符:

th:text="'The name of the user is ' + ${user.name}"

下面是我发现的一个有效的例子:

<p th:text="${bean.field} + '!'">Static content</p>

然而,事实并非如此:

<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>

从逻辑上讲,这应该工作,但它不是,我做错了什么?


美芬:

<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>2.0.16</version>
<scope>compile</scope>
</dependency>

下面是我如何设置 TemplateEngine 和 TemplateResolver:

<!-- Spring config -->
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="order" value="1"/>
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="fileTemplateResolver"/>
<property name="templateResolvers">
<list>
<ref bean="templateResolver"/>
</list>
</property>

ThymeleafTemplatingService:

@Autowired private TemplateEngine templateEngine;
.....
String responseText = this.templateEngine.process(templateBean.getTemplateName(), templateBean.getContext());

Java:

public abstract class AbstractTemplate {
private final String templateName;
public AbstractTemplate(String templateName){
this.templateName=templateName;
}
public String getTemplateName() {
return templateName;
}
protected abstract HashMap<String, ?> getVariables();
public Context getContext(){
Context context = new Context();
for(Entry<String, ?> entry : getVariables().entrySet()){
context.setVariable(entry.getKey(), entry.getValue());
}
return context;
}
}
133649 次浏览

But from what I see you have quite a simple error in syntax

<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>

the correct syntax would look like

<p th:text="${bean.field + '!' + bean.field}">Static content</p>

As a matter of fact, the syntax th:text="'static part' + ${bean.field}" is equal to th:text="${'static part' + bean.field}".

Try it out. Even though this is probably kind of useless now after 6 months.

You can concat many kind of expression by sorrounding your simple/complex expression between || characters:

<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>

Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:

th:text="${'static_content - ' + you_variable}"

We can concat Like this :


<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>