티스토리 뷰
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하는 String은 View의 이름이 된다. 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> → content에 html 소스가 포함되어 있다면 해당 코드 반영하여 보여줌 |
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/comments의 prodId매개변수가 로 설정된 댓글 페이지(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 파일로 치환하는 것으로 jsp의 include와 비슷한 동작을 함 |
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 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 파비콘 #파비콘 사이트에 적용
- jQuery #jQuery이미지슬라이드 #이미지슬라이드
- echart
- sw기술자평균임금 #2025년 sw기술자 평균임금
- 정보처리기사 #정보처리기사요약 #정보처리기사요점정리
- 자바스크립트 #javascript #math
- lg그램pro #lg그램 #노트북 #노트북추천 #lg노트북
- 무료폰트 #무료웹폰트 #한수원한돋움 #한수원한울림 #한울림체 #한돋움체
- 와이파이약할때
- 쇼팬하우어 #좋은책
- SQL명령어 #SQL
- thymeleaf
- 테스크탑무선랜카드 #무선랜카드 #아이피타이무선랜카드 #a3000mini #무선랜카드추천
- 파비콘사이즈
- jdk #jre
- 와이파이신호 #와이파이 #와이파이신호세게
- css미디어쿼리 #미디어쿼리 #mediaquery
- 썬크림 #닥터지썬크림 #내돈내산 #내돈내산썬크림 #썬크림추천 #spf50썬크림 #닥터지메디유브이울트라선
- 바지락칼국수 #월곡동칼국수 #칼국수맛집
- 좋은책 #밥프록터 #부의원리
- 좋은책
- 광주분식 #광주분식맛집 #상추튀김 #상추튀김맛집 #광주상추튀김
- 자바스크립트countiue
- 증폭기 #아이피타임증폭기
- 자바스크립트break
- 와이파이증폭기추천 #와이파이설치
- iptime와이파이증폭기 #와이파이증폭기설치
- ajax
- 연명의료결정제도 #사전연명의료의향서 #사전연명의료의향서등록기관 #광주사전연명의료의향서
- 자바스크립트정규표현식
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함