본문 바로가기
Study/SPRING

Spring Boot - Thymeleaf 사용법

by 멘탈은안녕하신가 2020. 10. 14.
728x90
반응형
  • Thymeleaf Spring Boot에서 공식적으로 지원하는 html 표현식
  • 기존 Spring에서 사용하던 JSP JSTL 대체
  • Thymeleaf 활용하는 document 객체 앞에는 th: 붙음

 

  • 사용 문법
    • th:block
      • thymeleaf 표현을 위한 document 임시 객체(html source 상에 태그가 표시되지 않음)
<th:block th:text="test"></th:block>

 

    • th:value = "${표현 값}"
      • input value 값을 삽입할 사용
      • 여러개의 값을 넣을 아래와 같이 + 기호 사용
      • 작은 따옴표를 활용해서 문자열을 조합 있음
<input type="text" th:value="${CD} + '의 명칭은 ' + ${NAME}">

 

    • th:text="{표현할 문자열}"
      • input 아닌 document 객체에 텍스트를 삽입
<span th:text="테스트"></span>

 

    • th:include
      • 페이지 삽입
<th:block th:include="test.html"></th:block>

 

    • 반복문
      • th:each="{별칭} : ${{controller에서 넘어온 데이터 key}}"
        • ) th:each="row : ${list}"
      • 주의) 반복 할 객체의 부모가 아니라 사용 될 해당 객체에 선언
        • ) table 아니고 tr 선언
          <table>
          	<tr th:each="row : ${list}">
          		<td></td>
          		~
          	</tr>
          </table>
      • 반복문에 index 같은 status 추가 경우 별칭 다음에 콤마를 써주고 뒤에 선언
        • 직접 명명 
          • th:each="{별칭}, status : ${{controller에서 넘어온 데이터 key}}"
          • 사용법 : ${status.{status}}
        • 데이터에서 활용
          • th:each="{별칭}, : ${{controller에서 넘어온 데이터 key}}"
          • 사용법 : ${별칭.{status}}
        • 사용 가능한 status
          • index : 0부터 시작하는
          • count : 1부터 시작하는
          • size : 데이터의
          • current : 현재 요소
          • even : 현재 반복이 짝수인지 여부
          • odd : 현재 반복이 홀수인지 여부
          • first : 현재 반복이 첫번째인지 여부
          • last : 현재 반복이 마지막인지 여부
      • select 콤보박스 활용
        • select 전체를 감싸주거나 option 값을 넣으려면 option에서 추가
  1. select 전체 감싸기  
<select th:field="*{gender}">
	<option th:value="'M'" th:text="Male"></option>
	<option th:value="'F'" th:text="Female"></option>
</select>

 

또는

<select th:field="*{percentage}">
	<option th:each="i : ${#numbers.sequence(0, 100)}" th:value="${i}" th:text="${i}"></option>
</select>​

 

 

2. option태그에 추가

<select>
	<option value="">선택</option>
	<option th:each="list : ${list}" th:value="${list.CD}" th:text="${list.NM}"></option>
</select>

 

  • 조건문
    • th:if="${{데이터} == {피연산자}"
      <div th:if="${{데이터} == {피연산자}">{조건에 맞으면 나올 document 객체}</div>​
       
    • 조건식에 조건이 여러개 경우 and, or 사용
      <div th:if="${not #lists.isEmpty({값})} and ${리스트[#numbers.formatInteger(값, 1)-1].{KEY}}"></div>
       
    • if-else
      <div th:if="${{데이터} == {피연산자}"></div>
      <div th:unless="${{데이터} == {피연산자}"></div>
      • 주의) 조건식은 if와 unless를 동일하게 써줌

 

  • Event
    • th:onclick="{function}([[${{parameter}}]])"
    • 이벤트 함수에 들어갈 파라미터는 대괄호 2개로 감싸줌
      <button type="button" th:onclick="javascript:test([[${row.num}]])">전송</button>

 

  • 삼항 연산자
    • th:{attribute}="${{데이터} == {피연산자} ? '{true 표현}' : '{false 표현}'}"
    • 삼항 연산자를 활용한 document 객체 attribute에서 활용법
      • false 부분이나 true 부분에 소괄호()  넣고 다시 삼항 연산자를 활용
<table>
	<tr th:each="row : ${list}" th:style="${row.MENU_LEVEL == 1 ? 'background-color:rgb(223, 255, 248);' : (row.MENU_LEVEL == 2 and row.MENU_URL == '-' ? 'background-color:rgb(223, 255, 0);' : '')}">
		<td th:text="${row.CD}"></td>
		<td th:text="${row.NM}"></td>
		<td><input type="checkbox" name="check" ></td>
		<td><input type="checkbox" name="check" ></td>
		<td><input type="checkbox" name="check" ></td>
	</tr>
</table>

 

  • 정적 파일 import 시
    • <link type="text/css" th:href="@{~.css}" />
    • <script th:src="@{~.js}"></script>
    • <img th:src="@{~.jpg}" />
    • 정적파일에 thymeleaf 변수 추가
      <img th:src="@{${{변수}}}">
      <img th:src="@{${'~?key='+{변수}}}">

 

 

참조1 : https://stackoverflow.com/questions/39165486/how-can-i-apply-style-to-a-div-based-on-condition-in-thymeleaf

참조2 : https://hakurei.tistory.com/302

참조3 : https://ifuwanna.tistory.com/200

참조4 : https://www.baeldung.com/thymeleaf-select-option

참조5 : https://stackoverflow.com/questions/29460618/inserting-an-image-from-local-directory-in-thymeleaf-spring-framework-with-mave

728x90
반응형

댓글