본문 바로가기
Spring 이해하기

Thymeleaf CheatSheet - 1 (basic)

by simplify-len 2021. 9. 6.

Thymeleaf CheatSheet - 1 (basic)

1. 텍스트 - text, 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>
</htm

결과
image-20210906130624898

주의 할 점
span th:inline="none" 의 의미는 타임리프가 [[...]] 를 해석하기 때문에, 화면에 [[...]] 글자를 보여줄 수 없기 때문에, 해당 태그가 붙어있는 타임리프안에서는 해석하지 말라는 옵션이다. 없으면 아래와 같이 나타남.

image-20210906131003994

2. 변수 - SpringEL

타임리프에서 변수를 사용할 떄는 변수 표현식 사용.

변수 표현식: ${...}

         @GetMapping("/variable")
     public String variable(Model model) {
         User userA = new User("userA", 10);
         User userB = new User("userB", 20);

         List<User> list = new ArrayList<>();
         list.add(userA);
         list.add(userB);

         final HashMap<String, User> map = new HashMap<>();
         map.put("userA", userA);
         map.put("userB", userB);

         model.addAttribute("user", userA);
         model.addAttribute("users", list);
         model.addAttribute("userMap", map);
         return "basic/variable";
     }
<body>

<h1>SpringEL 표현식</h1>
<ul>Object

    <li>${user.username} = <span th:text="${user.username}"></span></li>
    <li>${user['username']} = <span th:text="${user['username']}"></span></li>
    <li>${user.getUsername()} = <span th:text="${user.getUsername()}"></span></li>
</ul>

<ul>List

    <li>${users[0].username} span> = <span th:text="${users[0].username}"></span></li>
    <li>${users[0]['username']} = <span th:text="${users[0]['username']}"></span></li>
    <li>${users[0].getUsername()} = <span th:text="${users[0].getUsername()}"></span></li>
</ul>
<ul>Map

    <li>${userMap['userA'].username} = <span th:text="${userMap['userA'].username}"></span></li>
    <li>${userMap['userA']['username']} = <span th:text="${userMap['userA'] ['username']}"></span></li>
    <li>${userMap['userA'].getUsername()} = <span th:text="${userMap['userA'].getUsername()}"></span></li>

</ul>
</body>

map 으로 선언된 객체일 경우 인텔리제이에서 인식하지 못하는 경우도 있는것 같다.

지역 변수도 선언 가능하다. th:with 를 사용하면 지역 변수를 선언해서 사용할 수 있다.

어떻게?

<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
    <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>

3. 기본 객체들

대표적으로-

  • ${#request} - 만약 HttpServletRequest 객체에 접근해야 한다면, request.getParameter("data") 으로 접근 가능

  • ${#response}

  • ${#session}

  • ${#servletContext}

  • ${#locale}

좀 더 쉬운 방법으로 편의 객체 제공

  • HTTP 요청 파라미터 접근: param - ex)${param.paramData}

  • HTTP 세션 접근: session - ${session.sessionData}

  • 스프링 빈 접근: @ - ${@helloBean.hello('Spring!')}

    @GetMapping("/basic-objects")
    public String basicObjects(HttpSession session) {
        session.setAttribute("sessionData", "Hello Session");
        return "basic/basic-objects";
    }

    @Component("helloBean")
    static class HelloBean {
        public String hello(String data) {
            return "Hello" + data;
        }
    }
<body>

<h1>식 기본 객체 (Expression Basic Objects)</h1>
<ul>

    <li>request = <span th:text="${#request}"></span></li>
    <li>response = <span th:text="${#response}"></span></li>
    <li>session = <span th:text="${#session}"></span></li>
    <li>servletContext = <span th:text="${#servletContext}"></span></li>
    <li>locale = <span th:text="${#locale}"></span></li>
</ul>
<h1>편의 객체</h1>
<ul>
    <li>Request Parameter = <span th:text="${param.paramData}"></span></li>
    <li>session = <span th:text="${session.sessionData}"></span></li>
    <li>spring bean = <span th:text="${@helloBean.hello('Spring!')}"></span></li>
</ul>

</body>

image-20210906132708744

4. 유틸리티 객체와 날짜

  • https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-utility-objects

  • https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

  • Java8 시간

    <body>
    <h1>LocalDateTime</h1>
    <ul>
        <li>default = <span th:text="${localDateTime}"></span></li>
        <li>yyyy-MM-dd HH:mm:ss = <span th:text="${#temporals.format(localDateTime,'yyyy-MM-dd HH:mm:ss')}"></span></li>
    </ul>
    
    <h1>LocalDateTime - Utils</h1>
    <ul>
        <li>${#temporals.day(localDateTime)} = <span th:text="${#temporals.day(localDateTime)}"></span></li>
        <li>${#temporals.month(localDateTime)} = <span th:text="${#temporals.month(localDateTime)}"></span></li>
        <li>${#temporals.monthName(localDateTime)} = <span th:text="${#temporals.monthName(localDateTime)}"></span></li>
        <li>${#temporals.monthNameShort(localDateTime)} = <span th:text="${#temporals.monthNameShort(localDateTime)}"></span></li>
        <li>${#temporals.year(localDateTime)} = <span th:text="${#temporals.year(localDateTime)}"></span></li>
        <li>${#temporals.dayOfWeek(localDateTime)} = <span th:text="${#temporals.dayOfWeek(localDateTime)}"></span></li>
        <li>${#temporals.dayOfWeekName(localDateTime)} = <span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span></li>
        <li>${#temporals.dayOfWeekNameShort(localDateTime)} = <span th:text="${#temporals.dayOfWeekNameShort(localDateTime)}"></span></li>
        <li>${#temporals.hour(localDateTime)} = <span th:text="${#temporals.hour(localDateTime)}"></span></li>
        <li>${#temporals.minute(localDateTime)} = <span th:text="${#temporals.minute(localDateTime)}"></span></li>
        <li>${#temporals.second(localDateTime)} = <span th:text="${#temporals.second(localDateTime)}"></span></li>
        <li>${#temporals.nanosecond(localDateTime)} = <span th:text="${#temporals.nanosecond(localDateTime)}"></span></li>
    </ul>

    image-20210906133426401

유틸성 도구들은 필요할 때마다 docs 를 보고 찾아봐야 할 듯

5. URL 링크

타임리프에서 URL 링크를 생성할 때는 @{...} 문법 사용

    @GetMapping("/link")
    public String link(Model model) {
        model.addAttribute("param1", "data1");
        model.addAttribute("param2", "data2");
        return "basic/link";
    }
<h1>URL 링크</h1>
<ul>
    <li><a th:href="@{/hello}">basic url</a></li>
    <li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li>
    <li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li>
    <li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li>
</ul>

<a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a>

http://localhost:8080/hello?param1=data1&param2=data2

<a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a>

http://localhost:8080/hello/data1/data2

<a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a>

http://localhost:8080/hello/data1?param2=data2

참고 - https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#link-urls

6. 리터럴

    @GetMapping("/literal")
    public String literal(Model model) {
        model.addAttribute("data", "Spring!");
        return "basic/literal";
    }
<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>

image-20210906140010573

주의 해야 될점은 text 작성시 hello world 를 한번에 쓰려고 하면 안된다. 나눠서- 또는 " '(작은 따옴표) " 를 넣어서 문자열을 인식할 수 있도록 한다.

7. 연산

  • 비교연산
    • >(gt), <(lt), >=(ge), <=(le), !(not), ==(eq), !=(neq, ne)
  • 조건식
  • Elvis 연산자
  • No-Operation
    • _ 인 경우 마치 타임리프가 실행되지 않는 것처럼 동작됨.
    • Elvis 와 다른점은 타임리프 자체가 실행되지 않는 다는 점이다.
        @GetMapping("/operation")
    public String operation(Model model) {
        model.addAttribute("nullData", null);
        model.addAttribute("data", "Spring!");
        return "basic/operation";
    }
<body>

<ul>

    <li>산술 연산
        <ul>
            <li>10 + 2 = <span th:text="10 + 2"></span></li>
            <li>10 % 2 == 0 = <span th:text="10 % 2 == 0"></span></li>
        </ul>
    </li>
    <li>비교 연산
        <ul>
            <li>1 > 10 = <span th:text="1 &gt; 10"></span></li>
            <li>1 gt 10 = <span th:text="1 gt 10"></span></li>
            <li>1 >= 10 = <span th:text="1 >= 10"></span></li>
            <li>1 ge 10 = <span th:text="1 ge 10"></span></li>
            <li>1 == 10 = <span th:text="1 == 10"></span></li>
            <li>1 != 10 = <span th:text="1 != 10"></span></li>
        </ul>
    </li>
    <li>조건식
        <ul>
            <li>(10 % 2 == 0)? '짝수':'홀수' = <span th:text="(10 % 2 == 0)? '짝수':'홀수'"></span></li>
        </ul>
    </li>
    <li>Elvis 연산자
        <ul>
            <li>${data}?: '데이터가 없습니다.' = <span th:text="${data}?:'데이터가 없습니다.'"></span></li>
            <li>${nullData}?: '데이터가 없습니다.' = <span th:text="${nullData}?: '데이터가 없습니다.'"></span></li>
        </ul>
    </li>
    <li>No-Operation
        <ul>
            <li>${data}?: _ = <span th:text="${data}?: _">데이터가 없습니다.</span></li>
            <li>${nullData}?: _ = <span th:text="${nullData}?: _">데이터가없습니다.</span></li>
        </ul>
    </li>
</ul>

</body>

image-20210906141038836

8. 속성 값 설정

th:* 속성을 지정하면 타임리프는 기존 속성을 th:* 로 지정한 속성으로 대체한다. 기존 속성이 없다면 새로 만든다.

<input type="text" name="mock" th:name="userA" /> => 랜더링 후 <input type="text" name="userA" />

속성 추가

th:attrappend : 속성 값의 뒤에 값을 추가한다.

th:attrprepend: 속성 값의 앞에 값을 추가한다.

th:classappend: class 속성에 자연스럽게 추가한다.

<body>
<h1>속성 설정</h1>
<input type="text" name="mock" th:name="userA"/>

<h1>속성 추가</h1>
- th:attrappend = <input type="text" class="text" th:attrappend="class=' large'"/><br/>
- th:attrprepend = <input type="text" class="text" th:attrprepend="class='large '"/><br/>
- th:classappend = <input type="text" class="text" th:classappend="large"/><br/>

<h1>checked 처리</h1>
- checked o <input type="checkbox" name="active" th:checked="true"/><br/>
- checked x <input type="checkbox" name="active" th:checked="false"/><br/>
- checked x <input type="checkbox" name="active" checked="false"/><br/>
- checked=false <input type="checkbox" name="active" checked="false"/><br/>

</body>

결과 화면

<html>
<head>

    <meta charset="UTF-8">

    <title>Title</title></head>
<body>
<h1>속성 설정</h1>
<input type="text" name="userA"/>

<h1>속성 추가</h1>
- th:attrappend = <input type="text" class="text large"/><br/>
- th:attrprepend = <input type="text" class="large text"/><br/>
- th:classappend = <input type="text" class="text large"/><br/>

<h1>checked 처리</h1>
- checked o <input type="checkbox" name="active" checked="checked"/><br/>
- checked x <input type="checkbox" name="active"/><br/>
- checked x <input type="checkbox" name="active" checked="false"/><br/>
- checked=false <input type="checkbox" name="active" checked="false"/><br/>

</body>
</html>

9. 반복

th:each 를 사용해 반복한다.

<h1>기본 테이블</h1>
<table border="1">
    <tr>
        <th>username</th>
        <th>age</th>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.username}">username</td>
        <td th:text="${user.age}">0</td>
    </tr>
</table>

<h1>반복 상태 유지</h1>

<table border="1">

    <tr>
        <th>count</th>
        <th>username</th>
        <th>age</th>
        <th>etc</th>
    </tr>

    <tr th:each="user, userStat : ${users}">
        <td th:text="${userStat.count}">username</td>
        <td th:text="${user.username}">username</td>
        <td th:text="${user.age}">0</td>
        <td>
            index = <span th:text="${userStat.index}"></span>
            count = <span th:text="${userStat.count}"></span>
            size = <span th:text="${userStat.size}"></span>
            even? = <span th:text="${userStat.even}"></span>
            odd? = <span th:text="${userStat.odd}"></span>
            first? = <span th:text="${userStat.first}"></span>
            last? = <span th:text="${userStat.last}"></span>
            current = <span th:text="${userStat.current}"></span>
        </td>
    </tr>
</table>

두번째 테이블에서 사용한 user, userStat 에서 userStat 은 반복의 상태를 확인할 수 있도록 도와주는 파라미터

반복 상태 유지 기능

  • index: 0부터 시작하는 값
  • count: 1부터 시작하는 값
  • size: 전체 사이즈
  • even odd: 홀수,짝수 여부
  • first, last: 처음, 마지막 여부
  • current: 현재 객체

10. 조건부 평가

if, unless(if문 반대)

@GetMapping("/condition")
public String condition(Model model) {
    addUsers(model);
    return "basic/condition";
}

private void addUsers(Model model) {
    List<User> list = new ArrayList<>();
    list.add(new User("userA", 10));
    list.add(new User("userB", 20));
    list.add(new User("userC", 30));
    model.addAttribute("users", list);
}
<h1>if, unless</h1>
<table border="1">
    <tr>
        <th>count</th>
        <th>username</th>
        <th>age</th>
    </tr>
    <tr th:each="user, userStat : ${users}">
        <td th:text="${userStat.count}">1</td>
        <td th:text="${user.username}">username</td>
        <td>
            <span th:text="${user.age}">0</span>
            <span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
            <span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
        </td>
    </tr>
</table>

<h1>switch</h1>

<table border="1">

    <tr>
        <th>count</th>
        <th>username</th>
        <th>age</th>
    </tr>

    <tr th:each="user, userStat : ${users}">
        <td th:text="${userStat.count}">1</td>
        <td th:text="${user.username}">username</td>
        <td th:switch="${user.age}">
            <span th:case="10">10살</span>
            <span th:case="20">20살</span>
            <span th:case="*">기타</span>
        </td>
    </tr>
</table>

image-20210906143931350

if, unless - 타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다. 만약 다음 조건이 false 인 경우 <span>...<span> 부분 자체가 렌더링 되지 않음.

switch - * 은 만족하는 조건이 없을 때 사용하는 디폴트

11. 주석

<h1>예시</h1> 

<span th:text="${data}">html data</span>
<h1>1. 표준 HTML 주석</h1>
<!--
<span th:text="${data}">html data</span>
-->
<h1>2. 타임리프 파서 주석</h1>
<!--/* [[${data}]] */-->

<!--/*-->
<span th:text="${data}">html data</span>
<!--*/-->

<h1>3. 타임리프 프로토타입 주석</h1>
<!--/*/
<span th:text="${data}">html data</span>
/*/-->

2번 타임리프 파서 주석은 타임리프의 진짜 주석

3번 타임리프 프로토타임 주석의 의미는 타임리프에서만 렌더링 될 수 있도록 하는 것.

12. 블록

<th:block> 은 HTML 태그가 아닌 타임리프의 유일한 자체 태그.

block 을 왜 사용하는가? 타임리프의 특성상 HTML 태그안에 속성으로 기능을 정의해서 사용하는데, 사용하기 애매한 경우에 <th:block> 을 사용한다.

<th:block th:each="user : ${users}">

    <div>
        사용자 이름1 <span th:text="${user.username}"></span>
        사용자 나이1 <span th:text="${user.age}"></span>
    </div>

    <div>
        요약 <span th:text="${user.username} + ' / ' + ${user.age}"></span>
    </div>
</th:block>

실행 결과


<!DOCTYPE html>
<html>
<head>

    <meta charset="UTF-8">

    <title>Title</title></head>
<body>



    <div>
        사용자 이름1 <span>userA</span>
        사용자 나이1 <span>10</span>
    </div>

    <div>
        요약 <span>userA / 10</span>
    </div>


    <div>
        사용자 이름1 <span>userB</span>
        사용자 나이1 <span>20</span>
    </div>

    <div>
        요약 <span>userB / 20</span>
    </div>


    <div>
        사용자 이름1 <span>userC</span>
        사용자 나이1 <span>30</span>
    </div>

    <div>
        요약 <span>userC / 30</span>
    </div>

</body>
</html>

13. 자바스크립트 인라인

타임리프에서 자바스크립트를 편리하게 사용할 수 있는 인라인 기능

<script th:inline="javascript">

이를 사용한 것과 사용하지 않은 것의 문제점은 무엇인가?

  • 텍스트 렌더링
  • 자바스크립트 네추럴 템플릿
  • 객체
<!-- 자바스크립트 인라인 사용 전 -->
<script>
    var username = [[${user.username}]];
    var age = [[${user.age}]];

    //자바스크립트 내추럴 템플릿
    var username2 = /*[[${user.username}]]*/ "test username";

    //객체
    var user = [[${user}]];
</script>

<!-- 자바스크립트 인라인 사용 후 -->

<script th:inline="javascript">
    var username = [[${user.username}]];
    var age = [[${user.age}]];
    //자바스크립트 내추럴 템플릿
    var username2 = /*[[${user.username}]]*/ "test username";

    //객체
    var user = [[${user}]];

</script>

HTML 결과

<!-- 자바스크립트 인라인 사용 전 -->
<script>

    var username = userA;
    var age = 10;

    //자바스크립트 내추럴 템플릿
    var username2 = /*userA*/ "test username";

    //객체
    var user = BasicController.User(username=userA, age=10);
</script>

<!-- 자바스크립트 인라인 사용 후 -->

<script>

    var username = "userA";
    var age = 10;
    //자바스크립트 내추럴 템플릿
    var username2 = "userA";

    //객체
    var user = {"username":"userA","age":10};

</script>

자바스크립트 인라인 each

<script th:inline="javascript">

    [# th:each = "user, stat : ${users}"]
    var user[[${stat.count}]] = [[${user}]];
    [/]

</script>
<script>
    var user1 = {"username":"userA","age":10};
    var user2 = {"username":"userB","age":20};
    var user3 = {"username":"userC","age":30};
</script>

자세한 소스 코드 thymeleaf-basic

내용 출처 - 인프런 김영한님의 Spring MVC 웹 기술 2편

댓글