📘텍스트 - text, utext
타임리프의 가장 기본적인 기능 텍트를 출력하는 기능에 대해 알아보자.
타임리프는 기본적으로 HTML 태그의 속성에 기능을 정의해서 동작한다. HTML의 콘텐츠(Content)에 데이터를 출력할 때는 다음과 같이 th:text
를 사용하면된다.
HTML 태그의 속성이 아니라 HTML 콘텐츠 영역안에서 직접 데이터를 출력하고 싶으면 다음과 같이 [[...]]
를 사용하면 된다. 컨텐츠 안에서 직접 출력하기 = [[${data}]]
Controller
@GetMapping("text-basic")
public String textBasic(Model model) {
model.addAttribute("data", "Hello Spring!");
return "basic/text-basic";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>컨텐츠에 데이터 출력하기</h1>
<ul>
<li>th:text 사용 <span th:text="${data}"></span></li>
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>
</body>
</html>
</html>
📖Esacpe
HTML 문서는 <, > 같은 특수 문자를 기반으로 정의된다. 따라서 뷰 템플릿으로 HTML화면을 생성할 때는 출력하는 데이터에 이러한 특수 문자가 있는 것을 주의해서 사용해야 한다.
변경 전"Hello Spirng"
변경 후"Hello <b>Spirng"<b>
<b>
태그를 사용해서 Spring이라는 단어가 진하게 나오도록 코드를 입력하면 웹 브라우저에서 다음과 같은결과가 나온다.
웹 브라우저 : Hello <b>Spring!</b>
소스보기 : Hello <b>Spring!</b>
개발자가 의도한 것은 <b>가 있으면 해당 부분을 강조하는 것이 목적이었는데, <b>태그가 그대로 출력된다.
소스보기를 하면 < 부분이 <로 변경된 것을 확인할 수 있다.
📖HTML Entity
웹 브라우저는 <
를 HTML 태그의 시작으로 인식한다. 따라서 <
를 태그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데, 이것을 HTML Entity라 한다. 이렇게 HTML에서 사용하는 특수문자를 HTML Entity로 변경하는 것을 Escape라 한다. Thymeleaf가 제공하는 th:text
, [[...]]
는 기본적으로 Escape를 제공한다.
<
-> <
>
-> >
기타 수 많은 HTML 엔티티가 있다.
참고✒️ HTML Entity List
https://www.freeformatter.com/html-entities.html
Complete list of HTML entities - FreeFormatter.com
ISO 8859-1 Characters Full list of supported ISO-8859-1 characters. Notice that the names are case sensitive, hence if you want an uppercase letter, the name should also start with an uppercase letter. Character Entity Name Entity Number Description Spa
www.freeformatter.com
📖Unescape
Escape를 사용하지 않으려면 다음 두 기능을 제공한다.
th:text
->th:utext
[[...]]
->[(...)]
Controller
@GetMapping("/text-unescaped")
public String textUnescaped(Model model) {
model.addAttribute("data", "Hello <b>Spring!</b>");
return "basic/text-unescaped";
}
View
<!DOCTYPE html>
<html xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>text vs utext</h1>
<ul>
<li>th:text = <span th:text="${data}"></span></li>
<li>th:utext = <span th:utext="${data}"></span></li>
</ul>
<h1><span th:inline="none">[[...]] vs [(...)]</span></h1>
<ul>
<li><span th:inline="none">[[...]] = </span>[[${data}]]</li>
<li><span th:inline="none">[(...)] = </span>[(${data})]</li>
</ul>
</body>
</html>
th:inline="none"
: 타임리프는 [[...]]
를 해석하기 때문에, 화면에 [[...]]
글자를 보여줄 수 없다.
이 태그 안에서는 Thymeleaf로 해석하지 말라는 옵션이다.
주의💣
실제 서비스를 개발하다 보면 Escape를 사용하지 않아서 HTML이 정상 렌더링 되지 않는 수 많은 문제가 발생한다Escape를 기본적으로 하고, 꼭 필요할 때 unescape를 사용하자.
인프런 김영한님의 Sping강의 기반으로 공부한 것을 작성한 블로그입니다.
출처 : 인프런 -🔗 스프링 MVC 1편 by 우아한형제 김영한이사님
'Thymeleaf > Thymeleaf - 기본기능' 카테고리의 다른 글
Thymeleaf - URL 링크 (0) | 2023.04.03 |
---|---|
Thymeleaf - 유틸리티 객체와 날짜 (0) | 2023.04.02 |
Thymeleaf - 기본객체 (0) | 2023.04.02 |
Thymeleaf - SpringEL (0) | 2023.04.02 |
타임리프(Thymeleaf)란? (0) | 2023.04.02 |