【发布时间】:2015-08-29 18:58:53
【问题描述】:
短版
在使用 Spring 时应该如何在 Thymeleaf 中制作嵌套模板?它在 Spring 中的 th:object 属性中出现 asterisk notation is not supported ("*{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>
我们使用样本Address 对其进行测试。看起来不错。
我制作了一个person.html Thymeleaf 模板,它引用了这样的地址:
<span th:text="*{firstName}"></span>
<span th:object="${person.shippingAddress}">
<span th:include="fragments/address :: address"></span>
</span>
我们用一个例子来测试它。我什至可以引用相同的模板并将上下文设置为${person.mailingAddress}。到目前为止一切顺利。
现在让我们制作Order 模板。只是,嘿,等等。早些时候,在我们的person.html 文件中,我们说${person.shippingAddress},但现在我们需要它说${order.customer.shippingAddress}。 If I were not using Spring 我会将以下内容放入person.html:
<span th:text="*{firstName}"></span>
<span th:object="*{shippingAddress}">
<span th:include="fragments/address :: address"></span>
</span>
那样,无论我到达这里的路径是什么,我所关心的是我当前的上下文有一个shippingAddress。然后我可以直接使用person.html,也可以在我的order.html 模板中使用。
不幸的是我在 Spring am,所以我得到以下异常:
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)
要继续前进,我必须复制所有嵌套模板。在此示例中,我将有一个 person.html 和 th:object="${person.mailingAddress}" 调用 address.html,以及 person.html 的副本调用 orderCustomer.html,我们将行更改为 th:object="${order.customer.mailingAddress}",但在其他方面是相同的。
是否有一种解决方法可以让我重复使用模板?
【问题讨论】: