티스토리 뷰

Backend/SpringBoot

Thymeleaf 기본문법

Mo'Greene 2022. 12. 23. 20:55

기본설정 추가

xmlns:th="http://www.thymeleaf.org"

 

기본적인 배열을 'list'라는 이름으로 model에 담아보내보자

@GetMapping("/ex/ex1")
    public void ex1(Model model) {
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        model.addAttribute("list", list);
    }

 

타임리프 표현하는 두가지 방식
<h4>[[${list}]]</h4>
<h4 th:text="${list}"></h4>

 

반복문
<!--반복문 두가지 'th:each', 'th:block'-->
<ul>
    <li th:each="str : ${list}" th:text="${str}"></li>
</ul>

<ul>
    <th:block th:each="str : ${list}">
        <li>[[${str}]]</li>
    </th:block>
</ul>

 

반복문 status 변수 설정
<ul>
    <li th:each="str,status : ${list}">
        [[${status.index}]] -- [[${str}]]
    </li>
</ul>

html코드에서 status+명령어를 통해 사용

 

제어문 및 switch 사용
<ul>
    제어문 if
    <li th:each="str,status : ${list}">
        <span th:if="${status.odd}">odd -- [[${str}]]</span>
        <span th:if="${status.even}">even -- [[${str}]]</span>
    </li>

    삼항연산자
    <li th:each="str,status : ${list}">
        <span th:text="${status.odd} ? 'ODD -- ' + ${str} : 'even --' + ${str}"></span>
    </li>

    switch문
    <ul>
        <li th:each="str,status : ${list}">
            <th:block th:switch="${status.index % 3}">
                <span th:case="0">0</span>
                <span th:case="1">1</span>
                <span th:case="2">2</span>
            </th:block>
        </li>
    </ul>
</ul>

 

링크
<div>
    타임리프 링크처리
    <a th:href="@{/hello}">/hello</a>
    <p>
        링크를 key,value 값으로 보낼때 // utf-8 자동 한글 처리
        <a th:href="@{/hello(name='AAA', age=16)}">go parameter</a>
    </p>
</div>

 

 

아주 기초적인 타임리프 문법임에도 불구하고 잘 모르고 있었다.

'Backend > SpringBoot' 카테고리의 다른 글

Ajax 와 Json, 그리고 Rest방식  (1) 2022.12.26
ModelMapper  (0) 2022.12.25
Attempt to recreate a file for type * 에러  (0) 2022.12.23
인스턴스  (0) 2022.11.02
컬렉션 - 리스트, 셋, 맵  (0) 2022.06.22
Comments