Тимелеар: Конкатенация. Невозможно разобрать выражение.

У меня возникла проблема при попытке согласовать несколько значений в моем шаблоне. Согласно 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>

Логически, это должно работать, но его нет, что я делаю неправильно?


Maven:

<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());

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

Ответ 1

Но из того, что я вижу, у вас довольно простая ошибка в синтаксисе

<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}".

Попробуйте. Хотя это, вероятно, сейчас бесполезно сейчас через 6 месяцев.

Ответ 2

Вы можете конкатенировать много видов выражений, окружая ваше простое/сложное выражение между символами ||:

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

Ответ 3

Обратите внимание, что с | char, вы можете получить предупреждение с вашей IDE, например, я получаю предупреждение с последней версией IntelliJ, так что лучшее решение это использовать этот синтаксис:

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

Ответ 4

Мы можем согласиться, как это:

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