Nei*_*ilA 67 html java thymeleaf
我在尝试在模板中连接多个值时遇到问题.根据Thymeleaf 在这里我应该只是能够+他们在一起......
4.6加强文本
文本,无论是文字还是评估变量或消息表达式的结果,都可以使用+运算符轻松连接:
th:text="'The name of the user is ' + ${user.name}"
Run Code Online (Sandbox Code Playgroud)
以下是我发现的工作示例:
<p th:text="${bean.field} + '!'">Static content</p>
Run Code Online (Sandbox Code Playgroud)
然而,这不是:
<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>
Run Code Online (Sandbox Code Playgroud)
从逻辑上讲,这应该有效,但不是,我做错了什么?
Maven的:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>2.0.16</version>
<scope>compile</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
以下是我设置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>
Run Code Online (Sandbox Code Playgroud)
ThymeleafTemplatingService:
@Autowired private TemplateEngine templateEngine;
.....
String responseText = this.templateEngine.process(templateBean.getTemplateName(), templateBean.getContext());
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Eli*_*ine 158
但是从我看到的你在语法上有一个非常简单的错误
<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>
Run Code Online (Sandbox Code Playgroud)
正确的语法看起来像
<p th:text="${bean.field + '!' + bean.field}">Static content</p>
Run Code Online (Sandbox Code Playgroud)
事实上,语法th:text="'static part' + ${bean.field}"
等于th:text="${'static part' + bean.field}"
.
试试看.尽管这可能在6个月之后变得毫无用处.
Fer*_*azu 29
您可以通过在||
字符之间使用简单/复杂表达式来连接多种表达式:
<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>
Run Code Online (Sandbox Code Playgroud)
请注意,与 | char,您可以使用 IDE 收到警告,例如,我使用最新版本的 IntelliJ 收到警告,因此最好的解决方案是使用以下语法:
th:text="${'static_content - ' + you_variable}"
Run Code Online (Sandbox Code Playgroud)
我们可以像这样连接:
<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>
Run Code Online (Sandbox Code Playgroud)