本文介绍了Thymeleaf:串联-无法解析为表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在模板中合并多个值时遇到问题.根据Thymeleaf 此处,我应该能够+他们在一起...

I'm having an issue when trying to concat multiple values in my template.According to Thymeleaf here I should simply be able to + them together...

文本,无论它们是文字还是评估变量或消息的结果 表达式,可以使用+运算符轻松连接:

Texts, no matter whether they are literals or the result of evaluating variable or message expressions, can be easily concatenated using the + operator:

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

以下是我发现有效的示例:

Here is an example of what I found works:

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

但这不是:

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

从逻辑上讲,这应该可以,但是不能,我在做什么错了?

Logically, this should work but its not, what am I doing wrong?

行家:

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


这是我设置TemplateEngine和TemplateResolver的方式:


Here is how I've set my TemplateEngine and TemplateResolver up:

<!-- 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:

ThymeleafTemplatingService:

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

AbstractTemplate.java:

AbstractTemplate.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;
  }
}

推荐答案

但是从我看来,您在语法上有一个非常简单的错误

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

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

正确的语法看起来像

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

事实上,语法th:text="'static part' + ${bean.field}"等于th:text="${'static part' + bean.field}".

尝试一下.即使六个月后现在可能已经没用了.

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

这篇关于Thymeleaf:串联-无法解析为表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:27