[SpringBoot]-타임리프 기본 사용법(3)

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

inline 속성

SampleController 클래스 일부

 @GetMapping({"/exInline"})
    public String exInline(RedirectAttributes redirectAttributes){

        log.info("exInline...........");

        SampleDTO dto
                = SampleDTO.builder().sno(101L)
                					.first("..100")
                                    .last("..200")
                                    .regTime(LocalDateTime.now())
                                    .build();

        redirectAttributes.addFlashAttribute("result","success");
        redirectAttributes.addFlashAttribute("dto",dto);
        return "redirect:/sample/ex3";
    }
    
    @GetMapping("/ex3")
    public void ex3(){
        log.info("ex3.........");
    }

ex3.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${result}"></h1>
<h1 th:text="${dto}"></h1>

<script th:inline="javascript">
    var msg = [[${result}]];
    var dto = [[${dto}]];
</script>
</body>
</html>```

웹 브라우저

※ 별도의 처리가 없음에도 불구하고 문자열은 자동으로 ""이 추가되어 문자열이 되고, 같이 전송된 dto는 JSON 포맷의 문자열이 된 것을 볼 수 있다.

th:block

  • 별도의 태그가 필요하지 않아 반드시 태그에 붙어서 th:text나 th:value와 같은 제약이 없다.

  • 'sno가 5로 나눈 나머지가 0인 경우에는 sno를 출력하고, 그렇지 않다면 first를 출력하라'

<ul>
    <th:block th:each="dto : ${list}" >
        <li th:text="${dto.sno % 5 == 0}?${dto.sno}:${dto.first}"></li>
    </th:block>
</ul>

th:block은 실제화면에서는 html로 처리되지 않기 때문에 루프 등을 별도로 처리하는 용도로 사용된다.

링크 처리

  • '@{ }'를 이용해서 처리.

  • SampleController 클래스 일부

       @GetMapping({"/ex2","/exLink"})
       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);
       }
  • exLink.html
    	 <li th:each="dto : ${list}"><a th:href="@{/sample/exView}">[[${dto}]]</a>
- 파라미터 추가 (키, 값의 형태 추가) 

 <li th:each="dto : ${list}">
    <a th:href="@{/sample/exView/(sno=${dto.sno})}">[[${dto}]]</a>
  </li>
  
-path로 sno를 이용하고 싶을 때

 <li th:each="dto : ${list}">
    <a th:href="@{/sample/exView/{sno}(sno=${dto.sno})}">[[${dto}]]</a>
  </li>	
  

Thymeleaf의 기본 객체와 LocalDateTime

  • Thymeleaf는 내부적으로 기본 객체(basic objects)를 지원한다.
  • 기본 객체로는 문자, 숫자, 웹에서 사용되는 파라미터, request, response, session 등이 있어 편리하게 코드 작성이 가능하다.
  • 숫자나 날짜는 #numbers나 #dates 등으로 표현 가능하다.
  • ex)
    화면에 출력하는 sno를 모두 5자리로 만들어야 할 때
    <ul>
    	<li th:each="dto : ${list}">
           [[${#numbers.formatInteger(dto.sno,5)}]]
       </li>
    </ul>
  • LocalDate 타입이나 LocalDateTime 표현할 때
  • build.gradle에 해당 의존성 추가
  • #temporals라는 객체를 통해 format()으로 표현
<ul>
    <li th:each="dto : ${list}">
      [[${dto.sno}]] --- [[${#temporals.format(dto.regTime,'yyyy/MM/dd')}]]
    </li>
</ul>
profile
쓸때 대충 쓰지 말고! 공부하면서 써!

0개의 댓글