【问题标题】:Thymeleaf - Use local variable in Collection SelectionThymeleaf - 在集合选择中使用局部变量
【发布时间】:2022-01-20 17:40:35
【问题描述】:

在我的页面上,我有一个评论列表,每个评论都有一些 cmets。 从我的后端,我得到了所有评论的列表,以及所有 cmets 的列表。 每条评论都有review 属性,它决定了它所属的评论。

在每条评论下,我现在都在尝试展示相关的 cmets。 为此,我试图从我的comments 列表中过滤和循环所有 cmets,其中它们的父评论 (comment.review.getID()) 的 ID 等于当前评论的 ID (review.getID())。

这是我尝试的方法,但它不起作用。:

<div class="review" th:each="review : ${reviews}">
    <div class="review-comments" th:with="reviewID=${review.getID()}">
        <div class="comment" th:each="comment : ${comments.?[#this.review.getID() eq reviewID]}">

它会抛出这个错误:

Property or field 'reviewID' cannot be found on object of type 'de.firefuro.forum.entity.Comment'

那么如何将评论的评论 ID 与局部变量 reviewID(或与局部变量 review.getID())进行比较?

我也试过

<div class="review" th:each="review : ${reviews}">
    <div class="review-comments">
        <div class="comment" th:each="comment : ${comments.?[#this.review.getID() eq review.getID()]}">

但这也不起作用。它没有过滤任何东西。可能是因为它认为review 我的意思是comment.review。我无法使用本地的review 变量。

我该怎么做?

【问题讨论】:

    标签: java spring thymeleaf


    【解决方案1】:

    假设Comment 类有content 字段,我想这是正确的语法:

    <div th:each="review : ${reviews}">
        <div th:text="${review.id}"></div>
        <div th:each="comment : ${comments.?[review.id == __${review.id}__]}">
            <div th:text="${comment.content}"></div>
        </div>
    </div>
    

    【讨论】:

    • 哦,所以双下划线表示局部变量?
    • @FireFuro99 不完全是:__${review.id}__ 是一个 预处理 表达式,它在与comment.review.id 比较之前 进行评估。完整的语法是__${expr}__,而不仅仅是下划线。
    猜你喜欢
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多