개요
스프링 부트(Spring Boot) 환경에서 타임리프(Thymeleaf)를 사용해 뷰 화면을 구성하는 방법 및 사용할 수 있는 속성 관련 문법을 기록한다.
타임리프(Thymeleaf)란
💡 Thymeleaf 는 웹( 서블릿 기반) 환경과 웹이 아닌 환경 모두에서 작동할 수 있는 Java XML / XHTML / HTML5 템플릿 엔진 입니다 . MVC 기반 웹 애플리케이션 의 뷰 계층에서 XHTML/HTML5를 제공하는 데 더 적합 하지만 오프라인 환경에서도 모든 XML 파일을 처리할 수 있습니다. 이는 완전한 Spring Framework 통합을 제공합니다.
웹 애플리케이션에서 Thymeleaf는 JSP( JavaServer Pages ) 를 완전히 대체하는 것을 목표로 하며 브라우저에서 직접 열 수 있고 여전히 웹 페이지로 올바르게 표시되는 템플릿 파일 인 Natural Templates 의 개념을 구현합니다 .
Thymeleaf는 Apache License 2.0 에 따라 라이센스가 부여된 오픈 소스 소프트웨어 입니다 .
*From. 위키백과: https://en.wikipedia.org/wiki/Thymeleaf
쉽게 말해서 JSP와 비슷한 뷰 템플릿이라고 생각하면 될 것 같다. 지나가는 말에 따르면 JSP는 학교, 강의 등에서 교육용으로 많이 쓰이고 대부분 실무에서는 타임리프가 주류로 쓰인다고 한다. JSP와 비슷하지만 확연한 차이점도 존재한다.
- 네츄럴 템플릿 (Natural Templates)
- 순수 HTML을 최대한 유지하려는 성질을 말한다. 그에 따라 JSP와 달리 독립적으로 웹 브라우저에서 열어볼 수 있다.(동적 렌더링 제외)
- JAR 패키징 가능
- WAR만 가능한 JSP와 달리 JAR 패키징이 가능하다.
- 서블릿 변환 불가 (Servlet)
- Java코드를 포함하며 Servlet으로 변환되는 JSP와 달리 Servlet으로 변환이 불가하다. 즉, Java코드를 포함할 수 없으므로 비즈니스 로직으로부터 비교적 (강제적으로?) 자유롭다.
사전 준비
dependency 추가
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
HTML 내에 namespace 추가
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
...
기본 문법
기본적으로 JSP의 EL 표현식과 비슷하지만 태그 안(innerHTML)이 아닌 태그의 속성(attribute)에 작성해야한다. 타임리프의 모든 속성 문법은 th:○○○=”○○○” 의 형태를 지닌다.
데이터 접근/바인딩 표현식
- 변수 표현식: ${○○○}
JSP의 EL 표현식과 같이 기본적인 데이터 접근 표현식의 형태를 띈다.
<span th:text="*{lastname}"></span>
- 선택 변수 표현식: *{○○○}
$대신 *를 대괄호 앞에 붙이면 상위 태그의 th:object에 바인딩된 데이터 하위 속성에 접근할 수 있는 표현식이 된다. 아래 예시와 같이 상위 태그에 매핑된 데이터의 속성을 하위 태그에 바인딩할 수 있다.
<table th:object="${form}">
<tr>
<td>
<p>
<span th:text="*{lastname}"></span>
</p>
</td>
<td>
<p>
<span th:text="*{firstname}"></span>
</p>
</td>
</tr>
<tr>
<td>
<p>
<span th:text="*{phone_number}"></span>
</p>
</td>
<td>
<p>
<span th:text="*{address}"></span>
</p>
</td>
</tr>
<table>
- 링크 URL 표현식: @{○○○}
a 태그 내 th:href와 같은 attribute에 URL을 바인딩한다.
<a th:href="{form.file_link}" target="_blank">
<span th:text="${form.file_name}"></span>
</a>
타임리프 속성
- th:text
일반적인 텍스트를 활용하는 태그 안에 데이터를 바인딩해주는 속성. 유사한 속성으로 th:utext가 있는데 이는 escape처리를 하지 않고 그대로 바인딩해주는 차이점이 있다.
<span th:text="${lastname}"></span>
- th:object
하위 태그에서 속성에 접근할 수 있도록, 상위 태그에 Object를 바인딩해주는 속성
<table th:object="${form}">
<tr>
<td>
<p>
<span th:text="*{lastname}"></span>
</p>
</td>
</tr>
</table>
- th:href
a 태그에 URL을 바인딩해주는 속성. 보통 @{○○○} 형식의 표현식을 함께 사용한다.
<a th:href="@{file_link}" target="_blank">link</a>
- th:if
조건식을 작성할 수 있는 속성.
<th:block th:if="${type!='file'}">
<span>None</span>
</th:block>
- <th:block></th:block>
타임리프에서 HTML 속성 외에도 자체적인 태그를 제공하기도 한다. 위 태그는 반복문, 조건문 처럼 특정 HTML 태그에 속성을 추가하기 애매한 상황에서 th 속성만을 위한 태그가 되어준다.
<th:block th:if="${type.equals('textbox')}">
<span th:text="${textbox}"></span>
</th:block>
이 외에도 속성이 굉장히 많은데 공식 docs에서 다루고 있다.
Tutorial: Using Thymeleaf
1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a
www.thymeleaf.org
↓이 외에 속성들 펼치기
th:abbr | th:accept | th:accept-charset |
th:accesskey | th:action | th:align |
th:alt | th:archive | th:audio |
th:autocomplete | th:axis | th:background |
th:bgcolor | th:border | th:cellpadding |
th:cellspacing | th:challenge | th:charset |
th:cite | th:class | th:classid |
th:codebase | th:codetype | th:cols |
th:colspan | th:compact | th:content |
th:contenteditable | th:contextmenu | th:data |
th:datetime | th:dir | th:draggable |
th:dropzone | th:enctype | th:for |
th:form | th:formaction | th:formenctype |
th:formmethod | th:formtarget | th:fragment |
th:frame | th:frameborder | th:headers |
th:height | th:high | th:href |
th:hreflang | th:hspace | th:http-equiv |
th:icon | th:id | th:inline |
th:keytype | th:kind | th:label |
th:lang | th:list | th:longdesc |
th:low | th:manifest | th:marginheight |
th:marginwidth | th:max | th:maxlength |
th:media | th:method | th:min |
th:name | th:onabort | th:onafterprint |
th:onbeforeprint | th:onbeforeunload | th:onblur |
th:oncanplay | th:oncanplaythrough | th:onchange |
th:onclick | th:oncontextmenu | th:ondblclick |
th:ondrag | th:ondragend | th:ondragenter |
th:ondragleave | th:ondragover | th:ondragstart |
th:ondrop | th:ondurationchange | th:onemptied |
th:onended | th:onerror | th:onfocus |
th:onformchange | th:onforminput | th:onhashchange |
th:oninput | th:oninvalid | th:onkeydown |
th:onkeypress | th:onkeyup | th:onload |
th:onloadeddata | th:onloadedmetadata | th:onloadstart |
th:onmessage | th:onmousedown | th:onmousemove |
th:onmouseout | th:onmouseover | th:onmouseup |
th:onmousewheel | th:onoffline | th:ononline |
th:onpause | th:onplay | th:onplaying |
th:onpopstate | th:onprogress | th:onratechange |
th:onreadystatechange | th:onredo | th:onreset |
th:onresize | th:onscroll | th:onseeked |
th:onseeking | th:onselect | th:onshow |
th:onstalled | th:onstorage | th:onsubmit |
th:onsuspend | th:ontimeupdate | th:onundo |
th:onunload | th:onvolumechange | th:onwaiting |
th:optimum | th:pattern | th:placeholder |
th:poster | th:preload | th:radiogroup |
th:rel | th:rev | th:rows |
th:rowspan | th:rules | th:sandbox |
th:scheme | th:scope | th:scrolling |
th:size | th:sizes | th:span |
th:spellcheck | th:src | th:srclang |
th:standby | th:start | th:step |
th:style | th:summary | th:tabindex |
th:target | th:title | th:type |
th:usemap | th:value | th:valuetype |
th:vspace | th:width | th:wrap |
th:xmlbase | th:xmllang | th:xmlspace |
'개발 > 팁' 카테고리의 다른 글
Sourcetree 설치 (0) | 2024.01.17 |
---|---|
JAR 파일을 실행 바이너리 파일로 만들기 (0) | 2024.01.12 |
Spring - Cache (0) | 2024.01.12 |
톰캣 log 찾고 열람하는 방법 (1) | 2023.12.29 |
톰캣 버전 확인 (0) | 2023.12.28 |