Thymeleaf หลายเงื่อนไขเปลี่ยนสีพื้นหลัง

Jan 16 2021

เซลล์ตารางในคอลัมน์ accountDTO.state และ accountDTO.accountDTO ควรเปลี่ยนสีพื้นหลังขึ้นอยู่กับค่าข้อความของ accountDTO.state ฉันได้ลองสิ่งนี้แล้ว:

Thymeleaf - วิธีใช้สองสไตล์ (หรือมากกว่า) ตามเงื่อนไขที่ไม่สามารถใช้ร่วมกันได้

และฉันได้ค้นหาวิธีแก้ปัญหาเพิ่มเติม แต่ทุกคนใช้เงื่อนไขสำหรับค่าที่เป็นไปได้สองค่าหรือใน URL ด้านบนมีหลายเงื่อนไข ฉันมีเงื่อนไขเดียว แต่ฉันมีค่าที่เป็นไปได้ 9 ค่าในฟิลด์นั้น ผู้ใช้เลือกค่าสำหรับฟิลด์นั้นในเว็บเพจอื่น ในหน้านี้รายการจากฐานข้อมูลจะแสดงขึ้น

ตอนนี้ฉันได้ลองใช้คำสั่ง th: switch ภายในแท็ก td แล้ว แต่ฉันต้องเพิ่ม span หรือ div ภายใน td แต่ในกรณีนี้มันใช้ไม่ได้เซลล์จะไม่มีสี ฉันค้นหาบางอย่างเช่น if / else / if structure หรือ elif แต่ดูเหมือนว่าไม่มีเลย และฉันไม่สามารถทำซ้ำ th: if in a single tag. ฉันหวังว่าฉันจะสามารถใช้ th: switch ได้ แต่ทำไมมันถึงใช้ไม่ได้?

ด้านล่างนี้เป็นเพียงสวิตช์เวอร์ชันที่สั้นกว่าบางกรณีสำหรับตัวอย่างนี้ แต่ฉันจะต้องใช้ทั้งหมดเก้ากรณี

            <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;
}

อาจเป็นประโยชน์สำหรับการทำให้เอาต์พุตที่คล้ายกันสอดคล้องกันในหน้าแยกกัน