Home > front end >  Thymeleaf - Use local variable in Collection Selection
Thymeleaf - Use local variable in Collection Selection

Time:01-21

On my page I have a list of reviews, and each review has some comments. From my backend I get a list of all reviews, and a list of all comments. Each comment has review property, which determines the review it belongs to.

Under each review, I am now trying to show the associated comments. For this, I am trying to filter and loop over all comments from my comments list, where the ID of their parent review (comment.review.getID()) equals the ID of the current review (review.getID()).

This is how I am trying it, but it does not work.:

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

It throws this error:

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

So how can I compare the comment's review id with the local variable reviewID (or with the local review.getID())?

I also tried

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

but that did not work either. it did not filter anything. Probably because it thought that with review i mean comment.review. I can't manage to use the local review variable.

How do i do it?

CodePudding user response:

Assuming that Comment class has content field, I guess this would be the right syntax:

<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>
  •  Tags:  
  • Related