티스토리 뷰

WEB/기타

[Thymeleaf] 3. Thymeleaf 기본문법

silverline79 2024. 1. 19. 22:01

3.  Thymeleaf 기본문법

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${name}">Name</h1>
</body>
</html>
Thymeleaf 사용하기 위해 th 네임스페이스 추가
Controller에서 Model로 받아온 name 사용
<h1 th:text="${name}">Name</h1>

 

컨트롤러

@Controller
public class SampleController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "kepco");
return "hello";
}
}
@Controller 이기 때문에 return하는 StringView의 이름이 된다.
Model data를 받을 model을 선언

 

기본 표현식

[ https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax ]

간단한 표현 부울 연산
변수 표현식 : ${...}
선택 변수 표현식 : *{...}
메시지 표현 : #{...}
링크 URL 표현식 : @{...}
조각 표현식 : ~{...}
이진 연산자 : and,or
부울 부정(단항 연산자) : !,not
리터럴 비교 및 평등
텍스트 : 'one text', 'Another one!',
숫자 : 0, 34, 3.0, 12.3,
부울 : true,false
: null
리터럴 토큰 : one, sometext, main,
비교 : >, <, >=, <=( gt, lt, ge, le)
등호 연산자 : ==, !=( eq, ne)
텍스트 작업 조건 연산자
문자열 연결 : +
리터럴 대체 : |The name is ${name}|
If-then : (if) ? (then)
If-then-else : (if) ? (then) : (else)
Default : (value) ?: (defaultvalue)
산술 연산: Special tokens
이항 연산자: +, -, *, /,%
빼기 기호(단항 연산자): -
No-Operation: _

 

자주사용하는 표현식 예제 ( th:[속성]="서버 전달 받은 값 또는 조건식" )

Thymeleaf 3.x 에서는 inline 표현식이 추가되어 html 태그 없이 표현이 가능

[[$user.name]]

Title Description
th:text 서버에서 데이터 값을 그대로 출력
<span th:text="${user.name}">massage</span>
서버에서 user.name을 받아와서 massage부분에 출력
th:utext html 내용 / 이스케이프 처리하지 않고 html 반영<div th:utext="${content}"></div>
contenthtml 소스가 포함되어 있다면 해당 코드 반영하여 보여줌
th:value element value, checkbox, input  
<input type="text" th:value="${title}" />
서버 값에 따라 value값을 변경가능
th:with 변수값 지정 사용 가능 
<p th:with="authType = ${user.authType}+' Type'" th:text="${authType}"></p>
th:switchth:case switch-case
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
th:if 조건문 
<a href="comments.html"
th:href="@{/product/comments(prodId=${prod.id})}"
th:if="${not #lists.isEmpty(prod.comments)}">view</a>
제품 /product/commentsprodId매개변수가 로 설정된 댓글 페이지(URL 포함 ) 링크가 생성 id되지만 제품에 댓글이 있는 경우에만 가능
th:unless else 표현<p th:unless="${user.authType}=='facebook'" th:text="'not '+ ${user.authType}"></p>
th:each 반복문
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
th:fragment fragment명으로 다른 페이지에서 해당 fragment를 가져올 수 있음.
<div th:fragment="fragment-header"></div>
<div th:replace="/fragments/header.html :: fragment-header"></div>
th:replace html 태그를 replace에 정의된 다른 html 파일로 치환하는 것으로 jspinclude와 비슷한 동작을 함
th:href th:href="@{링크주소}
th:insert <div th:insert="~{commons :: main}">...</div>
th:attr 속성을 입력하고 속성이 설정된 태그의 속성 값을 변경하는 기능
<form action="subscribe.html" th:attr="action=@{/subscribe}">
<fieldset>
<input type="text" name="email" />
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
</fieldset>
</form>
th:object <div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
th:object태글르 통해서 변수 ${}로 객체를 받고 객체의 변숫값을 *{} 로 받음

 

[ https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes ]

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

 

속성 상속 우선 순위

[ https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#attribute-precedence ]

Order Feature Attributes
1 Fragment inclusion th:insertth:replace
2 Fragment iteration th:each
3 Conditional evaluation th:ifth:unlessth:switchth:case
4 Local variable definition th:objectth:with
5 General attribute modification th:attrth:attrprependth:attrappend
6 Specific attribute modification th:valueth:hrefth:src...
7 Text (tag body modification) th:textth:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

 

타임리프 주석

<!--/* 주석 문구 */--> <!--/* */--> 사이의 내용은 thymeleaf 처리후 제거됨
불필요한 주석을 클라이언트에 노출시키지 않게 처리가 가능
<!--/* 사이에 공백이 있으면 안되니 주의
<!--/*/ 주석 문구 /*/--> 정적페이지에서 주석으로 처리가 되고 thymeleaf처리 후 나타나게 되는 주석주석문구가 출력됨. 페이지내에 출력이 필요한 주석인 경우
<!--/*/ <!-- 주석 문구 --> /*/-->

 

'WEB > 기타' 카테고리의 다른 글

DBMS, JDBC, ORM, Hibernate  (0) 2024.01.20
[Thymeleaf] 4. Thymeleaf 템플릿 만들기  (0) 2024.01.19
[Thymeleaf] 2. Thymeleaf 사용 설정  (0) 2024.01.19
[Thymeleaf] 1. Thymeleaf 란?  (0) 2024.01.19
[SQL] TABLE 생성  (0) 2024.01.19
댓글