Thymeleaf 여러 조건, 배경색 변경

Jan 16 2021

accountDTO.state 및 accountDTO.accountDTO 열의 테이블 셀은 accountDTO.state의 텍스트 값에 따라 배경색을 변경해야합니다. 나는 이것을 시도했다 :

Thymeleaf-상호 배타적 인 조건을 기반으로 두 가지 이상의 스타일을 적용하는 방법

몇 가지 더 많은 솔루션을 검색했지만 모두가 가능한 두 가지 값에 대해 조건문을 사용하거나 위의 URL에는 여러 조건이 있습니다. 조건이 하나만 있지만 해당 필드에 가능한 값이 9 개 있습니다. 사용자가 다른 웹 페이지에서 해당 필드의 값을 선택합니다. 이 페이지에는 데이터베이스의 목록이 표시됩니다.

이제 td 태그 내부에서 th : switch 문을 사용해 보았지만 td 내부에 span 또는 div를 추가해야하지만이 경우 작동하지 않고 셀에 색상이 지정되지 않습니다. if / else / if 구조 또는 elif와 같은 것을 검색했지만 아무것도 보이지 않습니다. 그리고 단일 태그에서 th : if를 반복 할 수 없습니다. th : ​​switch를 사용할 수 있기를 바랍니다. 그런데 왜 작동하지 않습니까?

아래는이 예제의 경우 일부인 더 짧은 버전 스위치이지만 총 9 개의 케이스가 필요합니다.

            <tbody>
                <tr th:each = "accountDTO : ${listOfAccounts}"> <td th:text = "${accountDTO.accountDTO}"></td>
                    <td th:text = "${accountDTO.startBalance}"></td> <td th:text = "${accountDTO.currentBalance}"></td>
                    <td th:text = "${accountDTO.state}" th:switch = "${accountDTO.state}"
                    ><span th:case = "${accountDTO.state} == 'OUT_OF_USE'" th:appendstyle = "'background: red'"></span> <span th:case = "${accountDTO.state} == 'DEVICE'" th:appendstyle = "'background: green'"></span>
                    <span th:case = "${accountDTO.state} == 'LOCKED'" th:appendstyle = "'background: blue'"></span> </td> <td th:text = "${accountDTO.employee.employeeName}"></td>
                    <td><a th:href = "@{/editAccount/{id}(id=${accountDTO.idAccount})}" class="btn btn-primary btn-lg" id = "eBtn" th:data = "${accountDTO.idAccount}">Edit</a></td>
                </tr>
            </tbody>

답변

1 Richard Jan 16 2021 at 10:00

Thymeleaf 및 HTML을 단순화하기 위해 변수를 클래스로 사용하는 것을 고려하십시오. 그런 다음 CSS와 일관되게 형식을 설정할 수 있습니다. HTML은 다음과 같습니다.

<tbody>
    <tr th:each = "accountDTO : ${listOfAccounts}"> <td th:text = "${accountDTO.accountDTO}"></td>
        <td th:text = "${accountDTO.startBalance}"></td> <td th:text = "${accountDTO.currentBalance}"></td>
        <td th:text = "${accountDTO.state}" th:classappend = "${accountDTO.state}"></td>
        <td th:text = "${accountDTO.employee.employeeName}"></td> <td><a th:href = "@{/editAccount/{id}(id=${accountDTO.idAccount})}" class="btn btn-primary btn-lg" id = "eBtn" th:data = "${accountDTO.idAccount}">Edit</a></td>
    <tr>
</tbody>

그런 다음 CSS에서 다음과 같이보십시오.

td.OUT_OF_USE {
    background: red;
}
td.DEVICE {
    background: green;
}
td.LOCKED {
    background: blue;
}

별도의 페이지에서 유사한 출력을 일관되게 만드는 데 유용 할 수 있습니다.