텍스트 - text, utext
1.1 기본적인 텍스트 출력 기능
//controller에서
model.addAttribute("data", "Hello World"); //으로 데이터를 보낸다
이런식으로 작성하면 된다.
1.2 escape
웹 브라우저에서는 <를 HTML 태그의 시작으로 인식한다. 따라서 <,>와 같은 문자의 출력에 주의해야한다.
<,>를 태그의 시작이 아닌 문자로 표현하고자 하는것을 이스케이프(escape)라고 한다.
escape를 하지 않기 위해서는
th:text ㅡ> th:utext
[[...]] ㅡ> [(...)]
로 바꾸면 된다.
1.3 SpringEL
아래의 설명은 PDF파일을 참고했습니다.
Object
user.username : user의 username을 프로퍼티 접근 ㅡ> user.getUsername()
user['username'] : 위와 같음 ㅡ> user.getUsername()
user.getUsername() : user의 getUsername() 을 직접 호출
List
users[0].username : List에서 첫 번째 회원을 찾고 username 프로퍼티 접근 ㅡ> list.get(0).getUsername()
users[0]['username'] : 위와 같음
users[0].getUsername() : List에서 첫 번째 회원을 찾고 메서드 직접 호출
Map
userMap['userA'].username : Map에서 userA를 찾고, username 프로퍼티 접근 ㅡ> map.get("userA").getUsername()
userMap['userA']['username'] : 위와 같음
userMap['userA'].getUsername() : Map에서 userA를 찾고 메서드 직접 호출
th:with 를 사용하면 지역 변수를 선언해서 사용할 수 있다.
지역 변수는 선언한 테그 안에서만 사용할 수 있다.
1.4 기본 객체들
1.5 유틸리티 객체와 날짜
유틸리티 객체들이 너무 많아서 필요할 때 찾아서 사용해야할 것 같다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>LocalDateTime</h1>
<ul>
<li>default = <span th:text="${localDateTime}"></span></li>
<li>yyyy-MM-dd HH:mm:ss = <span th:text="${#temporals.format(localDateTime,'yyyy-MM-dd HH:mm:ss')}"></span></li>
</ul>
<h1>LocalDateTime - Utils</h1>
<ul>
<li>${#temporals.day(localDateTime)} = <span th:text="${#temporals.day(localDateTime)}"></span></li>
<li>${#temporals.month(localDateTime)} = <span th:text="${#temporals.month(localDateTime)}"></span></li>
<li>${#temporals.monthName(localDateTime)} = <span th:text="${#temporals.monthName(localDateTime)}"></span></li>
<li>${#temporals.monthNameShort(localDateTime)} = <span
th:text="${#temporals.monthNameShort(localDateTime)}"></span></li>
<li>${#temporals.year(localDateTime)} = <span th:text="${#temporals.year(localDateTime)}"></span></li>
<li>${#temporals.dayOfWeek(localDateTime)} = <span th:text="${#temporals.dayOfWeek(localDateTime)}"></span></li>
<li>${#temporals.dayOfWeekName(localDateTime)} = <span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span>
</li>
<li>${#temporals.dayOfWeekNameShort(localDateTime)} = <span
th:text="${#temporals.dayOfWeekNameShort(localDateTime)}"></span></li>
<li>${#temporals.hour(localDateTime)} = <span th:text="${#temporals.hour(localDateTime)}"></span></li>
<li>${#temporals.minute(localDateTime)} = <span th:text="${#temporals.minute(localDateTime)}"></span></li>
<li>${#temporals.second(localDateTime)} = <span th:text="${#temporals.second(localDateTime)}"></span></li>
<li>${#temporals.nanosecond(localDateTime)} = <span th:text="${#temporals.nanosecond(localDateTime)}"></span></li>
</ul>
</body>
</html>
1.6 URL 링크
단순한 URL
쿼리 파라미터
경로 변수
경로 변수 + 쿼리 파라미터
이렇게 활용 할 수 있다.
1.7 리터럴
리터럴은 소스 코드상에서 고정된 값을 말한다.
ex) "Hello"는 문자 리터럴, 10,20은 숫자 리터럴
타임리프에서 문자 리터럴은 항상 ' (작은 따옴표)로 감싸야 한다.
하지만 공백 없이 쭉 이어진다면 작은 따옴표를 생략할 수 있다.
1.8 연산
비교연산: HTML 엔티티 사용부분을 조심해야한다.
조건식: 자바 조건식과 유사하다.
Elvis 연산자: 조건식의 편의 버전이다.
No-Operation: _인 경우 타임리프가 실행되지 않는 것 처럼 동작한다. 이것을 잘 사용하면 HTML의 내용을 그대로 활용할 수 있다. 맨 마지막 예를 확인하면 된다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
<li>산술 연산
<ul>
<li>10 + 2 = <span th:text="10 + 2"></span></li>
<li>10 % 2 == 0 = <span th:text="10 % 2 == 0"></span></li>
</ul>
</li>
<li>비교 연산
<ul>
<li>1 > 10 = <span th:text="1 > 10"></span></li>
<li>1 gt 10 = <span th:text="1 gt 10"></span></li>
<li>1 >= 10 = <span th:text="1 >= 10"></span></li>
<li>1 ge 10 = <span th:text="1 ge 10"></span></li>
<li>1 == 10 = <span th:text="1 == 10"></span></li>
<li>1 != 10 = <span th:text="1 != 10"></span></li>
</ul>
</li>
<li>조건식
<ul>
<li>(10 % 2 == 0)? '짝수':'홀수' = <span th:text="(10 % 2 == 0)?'짝수':'홀수'"></span></li>
</ul>
</li>
<li>Elvis 연산자
<ul>
<li>${data}?: '데이터가 없습니다.' = <span th:text="${data}?: '데이터가
없습니다.'"></span></li>
<li>${nullData}?: '데이터가 없습니다.' = <span th:text="${nullData}?:
'데이터가 없습니다.'"></span></li>
</ul>
</li>
<li>No-Operation
<ul>
<li>${data}?: _ = <span th:text="${data}?: _">데이터가 없습니다.</span>
</li>
<li>${nullData}?: _ = <span th:text="${nullData}?: _">데이터가없습니다.</span></li>
</ul>
</li>
</ul>
</body>
</html>
1.9 속성 값 설정
th:* 속성을 지정하면 타임리프는 기존 속성을 th:* 로 지정한 속성으로 대체한다. 만약 기존 속성이 없다면 새로 만든다.
ex)
ㅡ> 타임리프 렌더링 후
속성 추가
th:attrappend : 속성 값의 뒤에 값을 추가한다.
th:attrprepend : 속성 값의 앞에 값을 추가한다.
th:classappend : class 속성에 자연스럽게 추가한다.
checked 처리
타임리프의 th:checked 는 값이 false 인 경우 checked 속성 자체를 제거한다.
ex)
ㅡ> 타임리프 렌더링 후:
1.10 반복
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>기본 테이블</h1>
<table border="1">
<tr>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
</tr>
</table>
<h1>반복 상태 유지</h1>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
<th>etc</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">username</td>
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
<td>
index = <span th:text="${userStat.index}"></span>
count = <span th:text="${userStat.count}"></span>
size = <span th:text="${userStat.size}"></span>
even? = <span th:text="${userStat.even}"></span>
odd? = <span th:text="${userStat.odd}"></span>
first? = <span th:text="${userStat.first}"></span>
last? = <span th:text="${userStat.last}"></span>
current = <span th:text="${userStat.current}"></span>
</td>
</tr>
</table>
</body>
</html>
반복시 오른쪽 컬렉션의 값을 하나씩 꺼내어 user라는 변수에 담아서 태그를 반복한다.
반복 상태 유지
반복의 두번째 파라미터를 설정해서 반복의 상태를 확인 할 수 있다. 두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명( user ) + Stat 가 된다. 여기서는 user + Stat = userStat 이므로 생략 가능하다.
- 반복 상태 유지 기능
index : 0부터 시작하는 값
count : 1부터 시작하는 값
size : 전체 사이즈
even , odd : 홀수, 짝수 여부( boolean )
first , last :처음, 마지막 여부( boolean )
current : 현재 객체
1.11 조건부 평가
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>if, unless</h1>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">1</td>
<td th:text="${user.username}">username</td>
<td>
<span th:text="${user.age}">0</span>
<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
</td>
</tr>
</table>
<h1>switch</h1>
<table border="1">
<tr>
<th>count</th>
<th>username</th>
<th>age</th>
</tr>
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">1</td>
<td th:text="${user.username}">username</td>
<td th:switch="${user.age}">
<span th:case="10">10살</span>
<span th:case="20">20살</span>
<span th:case="*">기타</span>
</td>
</tr>
</table>
</body>
</html>
if, unless
타임리프는 해당 조건이 맞지 않으면 태그 자체를 랜더링 하지 않는다.
switch
*은 만족하는 조건이 없을 때 사용하는 디폴트이다.
1.12 주석
1. 표준 HTML 주석
자바스크립트의 표준 HTML 주석은 타임리프가 렌더링 하지 않고, 그대로 남겨둔다.
2. 타임리프 파서 주석
타임리프 파서 주석은 타임리프의 진짜 주석이다. 렌더링에서 주석 부분을 제거한다.
3. 타임리프 프로토타입 주석
타임리프 프로토타입은 약간 특이한데, HTML 주석에 약간의 구문을 더했다.
HTML 파일을 웹 브라우저에서 그대로 열어보면 HTML 주석이기 때문에 이 부분이 웹 브라우저가
렌더링하지 않는다.
타임리프 렌더링을 거치면 이 부분이 정상 렌더링 된다.
쉽게 이야기해서 HTML 파일을 그대로 열어보면 주석처리가 되지만, 타임리프를 렌더링 한 경우에만
보이는 기능이다.
그닥 중요해 보이지 않아서 강의자료 복붙하였습니다.
1.13 블록
타임리프 특성상 HTML 태그안에 속성으로 기능을 정의해서 사용하는데, 위의 예시처럼 애매한 경우에 사용하면 된다. th:block 은 렌더링시 제거된다.
1.14 자바스크립트 인라인
= 자바스크립트를 편리하게 사용할 수 있게 해주는 기능
```
1.HTML 파일을 직접 열어도 동작하는 내추럴 템플릿 기능 제공
2.객체는 JSON으로 자동으로 변환해준다.
each 사용법
[# th:each="user, stat : ${users}"]
1.15 템플릿 조각
웹 페이지를 개발할 때 공통영역을 효율적이게 활용하기 위해 템플릿 조각과 레이아웃 기능을 사용한다.
template/fragment/footer :: copy : template/fragment/footer.html 템플릿에 있는 th:fragment="copy" 라는 부분을 템플릿 조각으로 가져와서 사용한다는 의미이다.
1.16 템플릿 레이아웃
코드 조각을 레이아웃에 넘겨서 사용하는 방법이다.
common_header(~{::title},~{::link}) 이 부분이 핵심이다.
::title 은 현재 페이지의 title 태그들을 전달한다.
::link 는 현재 페이지의 link 태그들을 전달한다.
ayoutExtendMain.html 는 현재 페이지인데,자체를 th:replace 를 사용해서 변경하는 것을 확인할 수 있다. 결국 layoutFile.html 에 필요한 내용을 전달하면서자체를 layoutFile.html 로 변경한다.
'백엔드 > 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술' 카테고리의 다른 글
검증2 - Validation (0) | 2023.03.15 |
---|---|
검증1 - Validation (0) | 2023.03.07 |
메시지, 국제화 (0) | 2023.01.28 |