Search code examples
springspring-bootthymeleaf

Spring boot thymeleaf for each statement


on the docotrs home page after signing in, i'm trying to write a for each statement in Spring boot thymeleaf that will pull and only display patients that have the my_doc_id that matches the doctorId. so something along the lines of

th:if{user.doc_id = user.my_doc_id} {
<h3 th:text="${user.firstName} + ' ' + ${user.lastName}"></h3>
}

but i know that's not right at all and i have no idea how to go about it.


Solution

  • Welcome to SO.

    There are various ways to accomplish this general problem. Here is one.

    You can use th:each to iterate through your list. If the IDs are equal, print the statement. You can optionally remove the <span> tag with th:remove="tag".

    <th:block th:each="user : ${doctorList}">
        <th:block th:if="${user.doc_id == my_doc_id}">
            <span th:text="${user.firstName} + ' ' + ${user.lastName}" th:remove="tag">[First Name, Last Name]</span>
        </th:block>
    </th:block>
    

    The test for equality will vary depending on the types that you are comparing. For example, if you are comparing an int and string, you can use ${#strings.equals(generic.value, #strings.toString(user.doc_id))} as in this post.

    th:block is nice because it doesn't create HTML tags at all, so you can use that as needed. It becomes a little tougher to read with many nested blocks though.