Thymeleaf
Thymeleaf ๋ฌธ๋ฒ ์ ๋ฆฌ
keepgoing
2021. 12. 21. 18:53
th:field, th:error๐
th:field="{ํ๋ ์ด๋ฆ}"์ ์ ์ธํ๋ฉด HTML์ด ๋ ๋๋ง๋ ๋, id, name์ ๊ฐ์ ๊ฐ์ผ๋ก ์ฒ๋ฆฌํด์ค๋ค.
์ฆ, `th:field="{name}"์
id = "name" name = "name"`๊ณผ ๊ฐ๋ค
//fieldError ๋ฉ์๋๋ฅผ ๋ฏธ๋ฆฌ ์ ์ธํด์ ์๋ฌ ๋ฐ์ ์ ๋นจ๊ฐ์ ํ
๋๋ฆฌ๊ฐ ํธ์ถ๋๋๋ก ์ค์
<style>
.fieldError {
border-color: #bd2130;
}
</style>
//th:field ์์
<input type="text" th:field="*{name}" class="form-control"
placeholder="์ด๋ฆ์ ์
๋ ฅํ์ธ์"
th:class="${#fields.hasErrors('name')}? 'form-control fieldError' : 'form-control'"> //ํ
๋๋ฆฌ ๋นจ๊ฐ์
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect date</p> //์๋ฌ๋ฉ์์ง ์ถ๋ ฅ
th:object๐
th:object
๋ ํผ์์ ์๋ฒ๋จ์ผ๋ก ๊ฐ์ ๋๊ธธ ๋ object์ ์ง์ ํ ๊ฐ์ฒด์ ๊ฐ์ ๋ด์ ๋๊ฒจ์ค ์ ์๋ค. ์ฆ, ํ๋ฉด์์ ์ ์ธํ ๊ฐ์ฒด์ ์ ๊ทผํ ์ ์๊ฒ ๋๋ค.
//th:object ์์
<form role="form" action="/members/new" th:object="${memberForm}" //ํ๋ฉด์์ memberForm ๊ฐ์ฒด์ ์ ๊ทผํ ์ ์๊ฒ ๋๋ค.
method="post">
th:each๐
ํด๋น ๊ฐ์ฒด์ ๋ด๊ธด ๊ฐ๋ค์ ์ฝ๋ ์ ํ์์ผ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค.
//th:each ์์
<select name="memberId" id="member" class="form-control">
<option value="">ํ์์ ํ</option>
<option th:each="member : ${members}"
th:value="${member.id}"
th:text="${member.name}" />
</select>
'?'์ ์๋ฏธ
<td th:text="${member.address?.city}"></td>
์ ์ฝ๋์์ address๋ค์ '?'๊ฐ ์๋๊ฑธ ํ์ธํ ์ ์๋๋ฐ ์ฌ๊ธฐ์์ ?์ ์๋ฏธ๋ null์ด ๋ค์ด๊ฐ๋ฉด ๋์ด์ ์งํํ์ง ์๋๋ค๋ ์๋ฏธ์ด๋ค.