Thymeleaf 사용 방법
Thymeleaf 사용 방법
제가 프로젝트에서 Thymeleaf를 사용한 이유는 회원의 메뉴리스트를 화면 이동이나 브라우저가 실행 될 때 마다 통신하여 DB를 값을 가지고 오게 되면 부하가 걸릴 수 있기 떄문에 DB의 값을 intercepter를 이용하여 session값을 넣어 thymeleaf를 사용하여 유동적으로 사용 하도록 개발 하는 일 이였습니다.(예시가 session을 기준으로 잡은 이유)
1 2 3 4 5 | <th:block th:if="${session.MENU_LIST !=null}"> <div th:each="testList : {session.test}"> <div th:text="${testList.name}"></div> </div> </th:block> | cs |
1. <th:block> , <th:if>
위 HTML 코드에서 첫번쨰 th:block 태그의 th:if 조건에 만족하는 경우에만 th:block 테그가 하위의 태그가 실행 된다.
즉 JAVA로 비유를 하면 그냥 단순한 if(){} 조건이라고 동일하다고 보면 될 것 같다.
2. <th:each>, <th:text>
th:each 태그는 반복문을 나타내며 해당 예시를 통하여 설명을 하면 testList.name값이 5개(a,b,c,d,e)라고 할 경우 th:each 선언된 하위 태그인 th:text가 5번 반복 실행되면서 <div text="a">, <div text="b">, <div text="c">, <div text="d">,<div text="e"> 가 생성되게 된다.
3. javascript
1 2 3 | <script th:inline="javascript"> var testList= /*[[ ${session.test} ]]*/ ""; </script> | cs |
th:inline="javascript" 태그를 사용하여 표현식을 통하여 서버 데이터를 스크립트에 사용할수 있다.
(이때 /*[[ ${session.test} ]]*/ 이 표현식 뒤에 ""이 값은 값이 존재 하지 않을 경우 ""대체 한다는 뜻이다.
이 선언을 하지 않을 경우 스크립트 오류를 발생할수 있다)
위 1번과 2번의 태그를 이용하여 실제로 프로젝트에서 사용한 코드 이다.
(조건으로 메뉴는 총 3개의 depth를 가지고 있다)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <th:block th:if="${session.MENU_LIST}" th:each="menuDepth1 : ${session.MENU_LIST}"> <th:block th:if="${menuDepth1.menuLevel == 1}"> <div class="gnb-item" data="bgColor1"> <span class="item" th:text="${menuDepth1.menuName}"></span> <div class="gnb-depth"> <div class="depth-inner"> <th:block th:each="menuDepth2 : ${menuDepth1.subMenuList}"> <th:block th:if="${menuDepth2.subMenuList == null}"> <div class="depth"> <a class="title" th:text="${menuDepth2.menuName}" th:href="'/' + ${menuDepth2.programPath}"></a> </div> </th:block> <th:block th:if="${menuDepth2.subMenuList != null}"> <div class="depth"> <span class="title" th:text="${menuDepth2.menuName}"></span> <div class="list" th:each="menuDepth3 : ${menuDepth2.subMenuList}"> <a class="link" th:text="${menuDepth3.menuName}" th:href="'/' + ${menuDepth3.programPath}"></a> </div> </div> </th:block> </th:block> </div> </div> </div> </th:block> </th:block> | cs |