티스토리 뷰

반응형

HTML의 태그가 아닌 오직 타임 리프만이 제공하는 유일한 자체 태그인 Block tag에 대해 살펴보고자 한다

 

Synthetic th:block

타임리프가 블록태그를 만든 이유는 주로 반복문에서 발생하는 문제점 때문인데

예를 들어 아래와 같이 두 개의 div 태그를 반복문으로 같이 돌리고 싶다면 매우 난감한 상황이 온다

<!-- th:block 미사용 -->
<div th:each="user : ${userList}">
	<span th:text="user.username}">username</span>
    <span th:text="user.age}">age</span>
</div>

<div th:each="user : ${userList}">
	<span th:text="${user.username} + ' & ' + ${user.age}">username&age</span>
</div>

이때 th:block 말 그대로 하나의 블록 처리를 하여 반복문을 돌리면 굉장히 간단하게 해결이 된다

<!-- th:block 사용 -->

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

th:block은 렌더링 될 때 사라지며 웹브라우저에는 본래 의도하던 두 개의 <div> 태그의 반복문 결과만 남게 된다

 

더보기

개인 학습을 위해 작성되는 글입니다.

제가 잘못 알고 있는 점에 대한 지적 / 더 나은 방향에 대한 댓글을 환영합니다.

 

참조 링크:

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2/dashboard

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 

반응형
댓글