모각코

절개와 지조 2차 모각코

potatoo 2023. 7. 8. 19:27
728x90

input과 label

label에서 for는 input의 id와 이름이 같아야한다.

<div th:each="region : ${regions}" class="form-check form-check-inline">
		<input type="checkbox" th:field="*{regions}" th:value="${region.key}" class="form-check">
		<label th:for="${#ids.prev('regions')}" th:text="${region.value}" class="form-check-label">서울</label>
</div>

#ids.prev는 동적으로 id를 할당해준다. 그래서 label의 for문에 넣어준다. each안에서 임의로 숫자를 부여

th:for="${#ids.prev('regions')}"

멀티 체크박스는 같은 이름의 여러 체크박스를 만들 수 있다. 그런데 문제는 이렇게 반복해서 HTML 태그를 생성할 때, 생성된 HTML 태그 속성에서 name 은 같아도 되지만, id 는 모두 달라야 한다. 따라서 타임리프는 체크박스를 each루프 안에서 반복해서 만들 때 임의로 1,2,3 숫자를 뒤에 붙여준다.

each로 체크박스가 반복 생성된 결과 - id 뒤에 숫자가 추가

  <input type="checkbox" value="SEOUL" class="form-check-input" id="regions1"
  name="regions">
  <input type="checkbox" value="BUSAN" class="form-check-input" id="regions2"
  name="regions">
 <input type="checkbox" value="JEJU" class="form-check-input" id="regions3"
  name="regions">
th:field="*{regions}"

히든 필드를 알아서 만들어준다. 원래는 null로 나오는데 이러면 true, false로 하는 것과 다르게 데이터가 넘어오지 않은것인지 false인 것인지 알 수 없다.

 

타임리프의 조건식

if, unless(if의 반대)

BasicController 추가

@GetMapping("/condition");
public String condition(Model model){
		addUsers(model);
		return "basic/condition";
}

/resources/templates/basic/condition.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
      <meta charset="UTF-8">
      <title>Title</title>
  </head>
  <body>
  <h1>if, unless</h1>
  <table border="1">
      <tr>
          <th>count</th>
          <th>username</th>
          <th>age</th>
      </tr>
      <tr th:each="user, userStat : ${users}">
          <td th:text="${userStat.count}">1</td>
          <td th:text="${user.username}">username</td>
          <td>
						<span th:text="${user.age}">0</span>
						<span th:text="'미성년자'" th:if="${user.age lt 20}"></span><!--20보다 작으면-->
					  <span th:text="'미성년자'" th:unless="${user.age ge 20}"></span><!--20보다 크거나 같으면-->
					</td> 
			</tr>
		</table>
		  <h1>switch</h1>
		<table border="1">
				<tr>
          <th>count</th>
          <th>username</th>
          <th>age</th>
	      </tr>
	      <tr th:each="user, userStat : ${users}">
          <td th:text="${userStat.count}">1</td>
          <td th:text="${user.username}">username</td>
          <td th:switch="${user.age}">
						<span th:case="10">10살</span> 
						<span th:case="20">20살</span>
						<span th:case="*">기타</span>
					</td> 
				</tr>
	  </table>
  </body>
</html>

if, unless

타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다.

만약 다음 조건이 false인 경우 <span>…<span> 부분 자체가 렌더링 되지 않고 사라진다.

<span th:text=”’미성년자’” th:if=”${user.age lt 20}”></span> //20보다 작으면 미성년자로 출력

switch

*은 만족하는 조건이 없을 때 사용하는 디폴트이다.

728x90