[SpringBoot] - Thymeleaf의 기본사용법

ACAI BERRY DEVELOVER·2023년 6월 19일
0
post-thumbnail

기본사용법을 알아보기 위해 우선 DTO 클래스를 추가하고 Controller도 작성한다.

  • SampleDTO 클래스
@Data
@Builder(toBuilder = true)
public class SampleDTO {

    private Long sno;

    private String first;

    private String last;

    private LocalDateTime regTime;

}
  • SampleController
@Log4j2
@Controller
@RequestMapping("/sample")
public class SampleController {

    @GetMapping("/ex1")
    public void ex1(){
        log.info("ex1 . . . . . . ");
    }

    @GetMapping({"/ex2"})
    public void exModel(Model model){   //인트스트림 => 객체로 형변환
        List<SampleDTO> list = IntStream.rangeClosed(1, 20).asLongStream().mapToObj(

                i -> {
                    SampleDTO dto = SampleDTO.builder().sno(i).first("First.." + i)
                            .last("Last.." + i)
                            .regTime(LocalDateTime.now()).build();
                    return dto;

                }

        ).collect(Collectors.toList());

        model.addAttribute("list",list);
    }
}
  • 화면 (ex1, ex2)
  • /sample/ex1
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 th:text="${'Hello World'}"></h1>
</body>
</html>
  • /sample/ex2
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--/*<li th:each="dto : ${list}">
         [[${dto}]]
     </li></ul>

<li th:each="dto, state: ${list}">
    [[${state.index}]] -- [[${dto}]]
</li>*/-->



        <!--/* 제어문 처리 */-->
       <ul> <li th:each="dto, state : ${list}" th:if="${dto.sno % 5 == 0}">
            [[${dto}]]
        </li>
       </ul>



   <!--/*
    th:if, th:unlesss, sno가 5로 나눈 나머지가 0인 경우에는 sno만을 출력하고,
        그렇지 않으면 SampleDTO의 first를 출력하라
    <li th:each="dto, state: ${list}">
            <span th:if="${dto.sno % 5 ==0}" th:text="${'-----------' +dto.sno}"></span>
            <span th:unless="${dto.sno % 5 ==0}" th:text="${dto.first}"></span>
                    </li>
      <ul>
        <li th:each="dto : ${list}" th:text="${dto.sno % 5 ==0}?${dto.sno}"></li>
        </ul>*/-->



</body>
</html>

반복문 처리

  • th:each = "변수 : ${목록}"

    <li th:each="dto : ${list}">
            [[${dto}]]
        </li>
  • < li > 태그 내에서는 'dto'라는 변수를 만들어 사용하고 Model로 전달된 데이터는 ${list} 를 이용해 처리하고 있다.
  • < li > 태그 안쪽에 사용된 '[[ ]]'는 인라인 표현식으로 별도의 태그 속성을 지정하지 않고 사용할 때 유용하다.

반복문의 상태(state)객체

  • 반복문에는 상태(state)객체가 있다.
  • 상태(state)객체를 이용하면 순번, 인덱스 번호, 홀/짝수등을 지정할 수 있다.

<li th:each="dto, state: ${list}">
    [[${state.index}]] -- [[${dto}]]
</li>

제어문 처리

  • th:if ~ unless
  • 삼항연산자

반복문과 if처리

- sno의 값이 5의 배수인 것만 출력하라.

<ul>
    <li th:each="dto : ${list}" th:if="${dto.sno % 5 == 0}">
        [[${dto}]]
    </li>
</ul>

- 결과 
SampleDTO(sno=5, first=First..5, last=Last..5, regTime=2023-06-19T19:20:33.613594)
SampleDTO(sno=10, first=First..10, last=Last..10, regTime=2023-06-19T19:20:33.613618)
SampleDTO(sno=15, first=First..15, last=Last..15, regTime=2023-06-19T19:20:33.613644)
SampleDTO(sno=20, first=First..20, last=Last..20, regTime=2023-06-19T19:20:33.613667)

th:if와 th:unless를 이용하면 상황에 맞게 다른 내용이 출력 가능하다.


- sno가 5로 나눈 나머지가 0인 경우에는 sno만을 출력하고, 그렇지 않다면 SampleDTO의 
  first를 출력하라
  
  <ul>
    <li th:each="dto: ${list}">
        <span th:if="${dto.sno % 5 == 0}" th:text="${'--------------------' + dto.sno}"></span>
        <span th:unless="${dto.sno % 5 == 0}" th:text="${dto.first}"></span>
    </li>
</ul>

- 결과 
First..1
First..2
First..3
First..4
--------------------5
First..6
First..7
First..8
First..9
--------------------10
First..11
First..12
First..13
First..14
--------------------15
First..16
First..17
First..18
First..19
--------------------20

삼항연산자 처리

dto객체의 sno를 5로 나눈 나머지가 0이면 sno를 출력하고 그렇지 않으면 dto객체를 출력하라.

<ul>
    <li th:each="dto, state : ${list}" th:text="${dto.sno % 5 == 0}?${'........'+dto.sno}:${dto}"></li>

</ul>
profile
쓸때 대충 쓰지 말고! 공부하면서 써!

0개의 댓글