BackEnd/Thymeleaf

[Thymeleaf] Literals

샤아이인 2022. 1. 26.

인프런 김영한님의 Spring강의에서 공부한것을 올리며, Thymeleaf의 경우 unit 단위로 공부후 각각 정리하는 글을 작성하겠습니다.

[Thymeleaf] Literals

 

리터럴

타임리프에는 대표적으로 다음과 같은 리터럴들이 있습니다. 리터럴은 일반적으로 소스 코드상에 고정된 값을 말하죠!

 

문자: 'hello'

숫자: 10

불린: true, false

null: null

 

타임리프에서는 문자 리터럴의 경우 항상 '(작은 따옴표) 로 감싸줘야 합니다.

<span th:text="'hello'">
 

문제는... 이게 항상 ' 로 감싸는게 귀찮다는 점 이죠.

따라서 타임리프에서는 공백없이 쭉 이어진 경우 의미있는 토큰으로 인식하여 다음과 같이 따옴표를 생략할수도 있습니다.

<span th:text="hello">
 

하지만 다음과 같이 공백이 있는경우에는 오류를 발생합니다. 다음 코드는 따옴표로 감싸줘야 합니다.

<span th:text="'hello world!'"></span>
 

예제

우선 컨트롤러부터 하나 만들어 봐야겠죠?

@GetMapping("/literal")
public String literal(Model model){
    model.addAttribute("data", "zbqmgldjfh!");
    return "basic/literal";
}
 

이를 처리할 뷰는 다음과 같습니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>리터럴</h1>
<ul>
    <li>'hello' + ' world!' = <span th:text="'hello' + ' world!'"></span></li>
    <li>'hello world!' = <span th:text="'hello world!'"></span></li>
    <li>'hello ' + ${data} = <span th:text="'hello ' + ${data}"></span></li>
    <li>리터럴 대체 |hello ${data}| = <span th:text="|hello ${data}|"></span></li>
</ul>

</body>
</html>
 

실행 결과는 다음과 같습니다.

[Thymeleaf] Literals - 				
    
    	예제

맨 마지막에 사용한 리터럴 대체에 대하여 좀더 알아봅시다!

 

리터럴 대체 - |...|

|...| : 이렇게 사용합니다.

타임리프에서 문자와 표현식 등은 분리되어 있기 때문에 더해서 사용해야 하죠.

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
 

다음과 같이 리터럴 대체 문법을 사용하면, 더하기 없이 편리하게 사용할 수 있다.

<span th:text="|Welcome to our application, ${user.name}!|"> 
 

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

[Thymeleaf] 속성 값 설정  (0) 2022.01.27
[Thymeleaf] 연산  (0) 2022.01.26
[Thymeleaf] URL 링크  (0) 2022.01.26
[Thymeleaf] 유틸리티 객체와 날짜  (0) 2022.01.26
[Thymeleaf] 기본 객체들  (0) 2022.01.26

댓글