Java Spring中的嵌套Thymeleaf模板
短版 使用Spring时,如何在Thymeleaf中创建嵌套模板?它出现在Spring中的Java Spring中的嵌套Thymeleaf模板,java,spring,thymeleaf,Java,Spring,Thymeleaf,短版 使用Spring时,如何在Thymeleaf中创建嵌套模板?它出现在Spring中的th:object属性中(“*{mailingAddress}”)。是否有变通/不同的标签可供使用 长版本 例如,假设我有以下课程: class Address { String street; } class Person { Address mailingAddress; Address shippingAddress; } class Order { int orderNo; Person custo
th:object
属性中(“*{mailingAddress}”
)。是否有变通/不同的标签可供使用
长版本
例如,假设我有以下课程:
class Address { String street; }
class Person { Address mailingAddress; Address shippingAddress; }
class Order { int orderNo; Person customer; }
所以我制作了一个address.html
Thymeleaf模板:
<span th:text="*{street}"></span>
我们用一个例子来测试它。我甚至可以引用同一个模板,并将上下文设置为${person.mailingAddress}
。到目前为止还不错
现在让我们制作订单
模板。只是,嘿,等等。前面,在我们的person.html
文件中,我们说了${person.shippingAddress}
,但现在我们需要它说${order.customer.shippingAddress}
。我将以下内容放入person.html
:
<span th:text="*{firstName}"></span>
<span th:object="*{shippingAddress}">
<span th:include="fragments/address :: address"></span>
</span>
若要继续,我必须复制所有嵌套模板。在这个例子中,我将有一个person.html
和th:object=“${person.mailingAddress}”
调用address.html
,还有一个person.html
的副本调用orderCustomer.html
,其中我们将行更改为th:object=“${order.customer.mailingAddress}
,但在其他方面是相同的
有没有一项工作可以让我重复使用模板?您可以向github中的thymeleaf开发人员报告一个bug,或者通过项目添加此功能并说服Daniel Fernández接受它 否则,他在StackOverflow中可用。您只需向他发送一条消息,说明集成此功能的可能性 除此之外,我们没有什么可以做的,而是坚持将
th:object=“${person.mailingAddress}”和th:object=“${order.customer.mailingAddress}”放在每次导入之外的方法
<span th:text="*{firstName}"></span>
<span th:object="*{shippingAddress}">
<span th:include="fragments/address :: address"></span>
</span>
org.thymeleaf.exceptions.TemplateProcessingException:
The expression used for object selection is *{shippingAddress},
which is not valid: only variable expressions (${...}) are
allowed in 'th:object' attributes in Spring-enabled environments.
(include:510)
at org.thymeleaf.spring4.processor.attr.SpringObjectAttrProcessor.validateSelectionValue(SpringObjectAttrProcessor.java:73)
at org.thymeleaf.standard.processor.attr.AbstractStandardSelectionAttrProcessor.getNewSelectionTarget(AbstractStandardSelectionAttrProcessor.java:69)
at org.thymeleaf.processor.attr.AbstractSelectionTargetAttrProcessor.processAttribute(AbstractSelectionTargetAttrProcessor.java:61)