리터럴(Literals)
리터럴은 소스 코드상에 고정된 값을 말하는 용어이다.
예를 들어서 다음 코드에서 "Hello" 는 문자 리터럴, 10 , 20 는 숫자 리터럴이다.
String a = "Hello"
int a = 10 * 20
타임리프는 다음과 같은 리터럴이 있다
문자 : 'hello'
숫자 : 10
불린 : true, false
null : null
타임리프에서 문자 리터럴은 항상 '
(작은 따옴표)로 감싸야 한다.<span th:text="'hello'">
그런데 문자를 항상 '
로 감싸는 것은 너무 불편하다. 공백 없이 쭉 이어진다면 하나의 의미있는 토큰으로 인지해서
다음과 같이 작은 따옴표를 생략할 수 있다.
룰: A-Z
,a-z
,0-9
,[]
,.
,-
,_
<span th:text="hello">
✏️오류<span th:text="hello world!"></span>
문자 리터럴은 원칙상 '
로 감싸야하며, 중간에 공백이 있으면 하나의 의미있는 토큰으로 인식되지않는다.
✏️수정<span th:text="'hello world!'"></span>
이렇게 '
로 감싸면 정상 동작한다.
예제
Controller
@GetMapping("/literal")
public String literal(Model model) {
model.addAttribute("data", "Spring!");
return "basic/literal";
}
View
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<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 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>
✏️리터럴 대체(Literal substitutions)<span th:text="|hello ${data}|">
마지막의 러터럴 대체 문법을 사용하면 마치 템플릿을 사용하는 것 처럼 편리하다.
인프런 김영한님의 Sping강의 기반으로 공부한 것을 작성한 블로그입니다.
출처 : 인프런 -🔗 스프링 MVC 1편 by 우아한형제 김영한이사님
'Thymeleaf > Thymeleaf - 기본기능' 카테고리의 다른 글
Thymeleaf - 속성 값 설정 (0) | 2023.04.03 |
---|---|
Thymeleaf - 연산 (0) | 2023.04.03 |
Thymeleaf - URL 링크 (0) | 2023.04.03 |
Thymeleaf - 유틸리티 객체와 날짜 (0) | 2023.04.02 |
Thymeleaf - 기본객체 (0) | 2023.04.02 |