Thymeleaf[리터럴]

조영재·2023년 6월 10일

Thymeleaf

목록 보기
6/15

리터럴은 소스 코드상에 고정된 값을 의미한다.

타임리프는 다음과 같은 리터럴이 있다.

  • 문자: 'hello'
  • 숫자: 10
  • 불린: true , false
  • null: null
  • 타임리프에서 문자 리터럴은 항상 ' (작은 따옴표)로 감싸야 한다.
    • <span th:text="'hello'">
  • 문자 리터럴에서 공백이 없다면 작은 따옴표를 생략할 수 있다.
    • 룰: A-Z , a-z , 0-9 , [] , . , - , _
    • <span th:text="hello">

basicController

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

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

basic/literal.html

<!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}|">
    리터럴 대체 문법을 사용하면 문자와 표현식을 더하지 않고 마치 템플릿을 사용하는 것 처럼 편리하게 사용가능

실행결과

profile
Just for fun

0개의 댓글