我在尝试在模板中连接多个值时遇到问题。 根据 Thymeleaf here,我应该能够将它们+在一起......
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>
Thymeleaf 模板服务:
@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;
}
}
但是从我看来,你在语法上有一个非常简单的错误
<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 个月后这可能有点没用了。
您可以通过将简单/复杂的表达式放在
||
字符之间来连接多种表达式:
<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>
请注意,与 | char,您可以通过 IDE 收到警告, 例如,我收到 IntelliJ 最新版本的警告, 所以最好的解决方案是使用这种语法:
th:text="${'static_content - ' + you_variable}"
我们可以这样连接:
<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>
顺便说一句,如果您需要将属性文件中的值与 Thymeleaf 属性中的其他值连接起来,令人惊讶的是,以下方法有效:
<input ...
th:attr="oninvalid=|setCustomValidity('#{main.my-main-error-message}')|" />
以上最终将呈现为:
<input ... oninvalid="setCustomValidity('Some error message here')" />