Thymeleaf

[Thymeleaf] 리터럴 Literal

GreedyBE 2022. 12. 25. 10:41

리터럴 (Literal)은 소스 코드의 고정된 값을 나타내는 표기법을 일컫는 말이다.

예를 들어 아래의 코드에서 문자열 "Thymeleaf" 는 문자 리터럴10, 20숫자 리터럴이다.

String s = "Thymeleaf";
int i = 10 * 20;

 

 

타임리프 제공 리터럴

  • 문자 : 'hello'
  • 숫자 : 10
  • 불린 : true, false
  • null : null

 

타임리프 사용 시 문자 리터럴에 대해서는 항상 '(작은 따옴표)로 하나하나 감싸줘야 한다.

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

 

하지만 적용 문자열이 공백 없이 이어진다면, 이를 하나의 의미 있는 토큰으로 인지하여 해당 작은 따옴표를 생략하는 것이 가능하다.

룰 : A-Z , a-z , 0-9 , [ ] , . , - , _
ex)    <span th:text="hello">      // 작은 따옴표 생략

 

 

Contoller

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

 

.HTML

<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>

 

결과

· 'hello' + ' world!' = hello world!
· 'hello world!' = hello world!
· 'hello ' + ${data} = hello Spring!
· 리터럴 대체 |hello ${data}| = hello Spring!

 

 

 

리터럴 대체 (Literal substitutions)
     <span th:text="|hello ${data}|">
다음과 같은 리터럴 대체 문법을 통해 마치 템플릿을 사용하는 것처럼 편리하게 표현할 수 있다.