지난 글에 이어서 타임리프 기본 문법을 정리하겠습니다.

 

지난 글 >> https://bboungg.tistory.com/26

 

타임리프 기본 문법 정리

인프런 김영한님 스프링부트 강의를 들으면서 타임리프의 기본 문법을 정리하였다. 우선 dependencies 에 추가해 준다. dependencies{ ... implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' ... } # 서

bboungg.tistory.com

 


Form 태그에서 사용예시 (th:field)

 

체크박스

보통 체크박스는 체크를 하지않고 데이터를 전송하면 서버에서는 null 값을 받을것이다.

하지만 아래와 같이 hidden으로 값을 전달하면 체크를 하지않으면 false 를 받는다.

<!-- single checkbox -->
<div>
 <div class="form-check">
 <input type="checkbox" id="open" name="open" class="form-check-input">
 <input type="hidden" name="_open" value="on"/> <!-- 히든 필드 추가 -->
 <label for="open" class="form-check-label">판매 오픈</label>
 </div>
</div>

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

여러 체크박스를 사용할때 컨트롤러에서 @ModelAttribute() 어노테이션을 사용하면 편하게 여러곳에서 사용할 수 있다.

아래의 예시처럼 하게되면 타임리프에서 "regions"로 Object를 받아서 사용하면 된다.

@ModelAttribute("regions")
public Map<String, String> regions() {
 Map<String, String> regions = new LinkedHashMap<>();
 regions.put("SEOUL", "서울");
 regions.put("BUSAN", "부산");
 regions.put("JEJU", "제주");
 return regions;
}

 

라디오 버튼

<!-- radio button -->
<div>
 <div>상품 종류</div>
 <div th:each="type : ${itemTypes}" class="form-check form-check-inline">
 <input type="radio" th:field="*{itemType}" th:value="${type.name()}" class="form-check-input">
 <label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label">
 BOOK
 </label>
 </div>
</div>

 

셀렉트박스

<!-- SELECT -->
<div>
 <div>배송 방식</div>
 <select th:field="*{deliveryCode}" class="form-select">
 <option value="">==배송 방식 선택==</option>
 <option th:each="deliveryCode : ${deliveryCodes}" th:value="${deliveryCode.code}" 
 th:text="${deliveryCode.displayName}">FAST</option>
 </select>
</div>

'개발공부 > Spring' 카테고리의 다른 글

스프링 인터셉터 (Interceptor)  (0) 2023.08.03
필터(Filter)  (0) 2023.08.02
데이터 검증 (Validation)  (0) 2023.07.31
타임리프에서 스프링부트 메시지 사용하기  (0) 2023.07.28
타임리프 기본 문법 정리  (0) 2023.07.26

+ Recent posts