【问题标题】:Nested Thymeleaf Templates in SpringSpring 中的嵌套 Thymeleaf 模板
【发布时间】: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.htmlth:object="${person.mailingAddress}" 调用 address.html,以及 person.html 的副本调用 orderCustomer.html,我们将行更改为 th:object="${order.customer.mailingAddress}",但在其他方面是相同的。

是否有一种解决方法可以让我重复使用模板?

【问题讨论】:

    标签: java spring thymeleaf


    【解决方案1】:

    您可以向 github 中的 thymeleaf 开发人员报告错误,或 fork 项目以添加此功能并说服 Daniel Fernández 接受它。

    https://github.com/thymeleaf/thymeleaf/issues

    否则,他可以在 StackOverflow 中使用。您可以简单地向他发送有关集成此功能的可能性的消息

    https://stackoverflow.com/users/550664/daniel-fern%C3%A1ndez

    除此之外,我们只能坚持将th:object="${person.mailingAddress}"th:object="${order.customer.mailingAddress}" 放在每个导入之外的方法。

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 2018-05-06
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 2019-02-20
      • 1970-01-01
      • 2017-07-30
      相关资源
      最近更新 更多