BackEnd/Thymeleaf

텍스트 - text, utext

연향동큰손 2024. 7. 15. 23:04

 

HTML의 콘텐츠에 데이터를 출력할때는 아래 코드와 같이 사용하면 된다.

 <span th:text="${data}">

 

HTML 테그의 속성이 아니라 HTML 콘텐츠 영역안에서 직접 데이터를 출력하고 싶으면 다음과 같이 [[ ... ]]를 사용하면 된다.

[[${data}]]

 

콘텐츠에 데이터를 출력하는 간단한 예제 코드를 통해 알아보자

 

 

<BasicController>

package hello.thymeleaf.basic;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/basic")
public class BasicController {

    @GetMapping("text-basic")
    public String textBasic(Model model){
        model.addAttribute("data","Hello,Spring!");
        return "basic/text-basic";
    }

    @GetMapping("text-unescaped")
    public String textUnescaped(Model model){
        model.addAttribute("data","<b>Hello,Spring!</b>");
        return "basic/text-unescaped";
    }
}

 

 

 

 

1. Escape
<!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>

 

 

실행 결과

 

 

 

 

2. Unescape

 

Unescape를 사용할때는 다음과 같이 변경 해줘야 한다.

 

th:text ==> th:utext

 

[[...]]  ==> [(...)]

 

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.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" ==> [[...]]안에서는 타임리프가 해석하지 말라는 옵션이다.

 

따라서 [[ ... ]]를 사용하면 글자 강조가 안되지만, [( ... )]를 사용하면 글자가 강조되는 것을 확인할 수 있다.

 

실행 결과

'BackEnd > Thymeleaf' 카테고리의 다른 글

타임리프-속성값 설정  (0) 2024.07.19
타임리프 - 리터럴  (0) 2024.07.16
타임리프-URL 링크  (0) 2024.07.16
타임리프-기본객체  (0) 2024.07.16
변수 - SpringEL  (1) 2024.07.15