Search code examples
springspring-bootspring-mvcthymeleafspring-thymeleaf

Count number of times a Thymeleaf if statement evaluates as true in a loop


I have a thymeleaf template that iterates over a List (chore completion objects), and prints a letter when an if condition is met (when a chore completion object has a certain chore_id and person_id). This results in a string of letters. How can I print out the number of letters rather than the string of repeating letters? Is thymeleaf able to have an iteration counter variable that could be used?

      <tr th:each="chore: ${chores}">
            <td>
                <span th:each="completion : ${completions}">
                    <span th:if="${(completion.chore?.chore_id) == chore.chore_id and (completion.person?.person_id) == persons[0].person_id}">T</span>
                </span>
            </td>
      </tr>

This image may clarify the intent.

enter image description here


Solution

  • It is perfectly fine to create a data structure in your controller that allows you to easily output what you need.

    For example, you could create a record (Or a class if you are on an older Java version) that has a field for the count you want to show and add instances of such records to your Model:

    @GetMapping
    public String showChoresOverview(Model model) {
    
      List<ChoresOverviewItemViewModel> items = ... // Get the info from your service and convert those object to ChoresOverviewItemViewModel instances in the controller
    
      mode.addAttribute("items", items);
    
      return "chores/index"; //name of you Thymeleaf template
    }
    
    private record ChoresOverviewItemViewModel(String description, String lastCompletionUser, Map<String,Integer> thisMonthUserToCountMapping) {
    }