[thymeleaf]타임리프 기본적인 사용방법

coldbrew·2023년 8월 20일
0

타임리프(thymeleaf)란?

자바 웹개발에 이상적인 '모던 서버 사이드 자바 템플릿 엔진'

  1. HTML과 유사(EL, JSTL)해서 디자이너와 개발자간의 협업을 쉽게 해준다.
  2. 확장성이 뛰어나며, 커스터마이징이 쉽다.
  3. 다양한 도구와 확장 프로그램으로 구성된 에코 시스템 제공(https://www.thymeleaf.org/ecosystem.html)

타임리프 템플릿

  1. HTML과 유사해서 편집 후 내용 확인이 쉽다.
  2. th:* 속성은 타임리프 전용 속성이며, 브라우저는 이를 무시한다.

tx:text는 ${...}을 해석해서 태그의 텍스트 노드로

<h1 th:text="${lastName}">lastName</h1>
<h1>[[${firstName}]]</h1>

문자열('...') 결합(+)과 리터럴 치환(|...|)

<h1 th:text="'My name is ' + ${lastName} + ' ' + ${firstName}"></h1>
<h1 th:text="|My name is ${lastName} ${firstName}|"></h1>

th:utext는 태그의<,>를 & lt;, & gt;로 바꾸지 않고 그대로

<span th:text="${'<i>Cold, Brew</i>'}"></span>
<span th:utext="${'<i>Cold, Brew</i>'}"></span>

조건부 처리(th:if, unless, switch) 예시로 if만 작성

<table>
    <tr th:each="item : ${list}">
        <td th:text="${item}"></td>
    </tr>
    <tr th:if="${list.size}==0">
        <td>게시물이 없습니다.</td>
    </tr>
</table>

lterable의 반복 처리는 th:each 또는 th:block 사용. 향상된 for문과 유사

<select name="" id="" multiple>
    <option th:each="opt : ${list}" th:value="${opt}">[[${opt}]]</option>
</select>

th:each를 사용하기 어려운 경우, th:block으로 처리(html문이 아니라 권장하지 않음)

<th:block th:each="opt : ${list}">
    <input type="checkbox" th:value="${opt}">[[${opt}]]<br>
</th:block>

URL링크 설정하기
1. @{...}를 경로로 변환.
2. application.properties에 server.servlet.context-path='' 추가

<a href="board.html" th:href="@{/board/list(bno=${bno}, type='L')}">abc</a>

0개의 댓글