Search code examples
htmlspring-mvcthymeleaf

How to find a specific element and get a field value from a list of objects in thymeleaf


I have this block in thymeleaf where I'm trying to show the name of a protocolVersion isntead of the id. I only have the Id so I pass the list of protocolVersion (protocolVersions) and I'm iterating over it to show the one that matches the id (1007 is just a test).

<th:block th:each="item: ${protocolVersions}">
  <tr th:if="${item.id == 1007}">
    <td th:text="${item.name}"></td>
  </tr>
</th:block>

I'm getting the error message:

Exception evaluating SpringEL expression: "item.id == 1007"

I've also tried something like this, as I've found it in one of the questions here:

<td th:if="${protocolVersions.?[id == '${excelMongoDoc.protocolVersionId}']}"
  th:text="${protocolVersions[id == '${excelMongoDoc.protocolVersionId}'].name}">
</td>

But this is not working either. Can anyone help please?

Thanks


Solution

  • The expression is simply: ${protocolVersions.^[id==1007].name}. So you could do this in your table:

    <tr>
      <td th:text="${protocolVersions.^[id==1007].name}"></td>
    </tr>
    

    If you want to check against a variable, rather than hardcoding 1007 something like this:

    <th:block th:with="check=1007">
      <td th:text="${protocolVersions.^[id==#root.check].name}"></td>
    </th:block>