티스토리 뷰

웹사이트를 개발하다보면, 회원목록, 일정내역 등 리스트 형태를 보여주는 화면이 적지 않음을 알 수 있다. 간단한 정보라면 html - table 태그로 하면 되지만, 건수가 많으면 페이징 처리도 해야 하고, 컬럼별로 내림차순/올림차순 정렬도 해야하고, 데이터 형식에 맞춰서 금액/날짜 등 포맷으로 변경해야 한다면, 잘 만들어진 그리드 라이브러리를 가져다 사용하는게 속편하다.

나 역시도 아래 화면처럼 회원목록을 보여줘야 하는 경우가 있었다. 검색기능, 총건수, 페이지당건수, 이전/다음 페이지 이동, 컬럼별 정렬, 필드 포맷, 왼쪽/가운데/오른쪽 정렬 등을 제공하는 datatables 를 사용하게 되었다.

 

DataTables | Table plug-in for jQuery

DataTables Table plug-in for jQuery Advanced tables, instantly DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any H

datatables.net

사이트에 가면 구현 방법과 옵션별 설명은 각종 예제 소스로 자세히 설명이 되고 있어 어렵지 않게 배울 수 있다. 우선 필요한 것은 html 파일에 라이브러리를 추가하는 일이다. jquery 라이브러리를 사용하는지 여부에 따라, 구현방법이 좀 달라지는데, 대부분의 예제들이 아직 jquery 를 사용하고 있어서 나 역시 jquery 도 추가했다. 아래 처럼 입력했다.

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.11.4/r-2.2.9/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.11.4/r-2.2.9/datatables.min.js"></script>

 

그리고 원하는 html 자리에 table 태그를 정의한다. 여기 소스중에 th: 가 붙은 부분은 Thymeleaf 라는 java 템플릿엔진인데, 안쓰시는 거면 무시하셔도 된다. 여기소스에는 class 속성이 중요하고, 반응형으로 컬럼을 동적으로 표현해야하는 경우 width="100%" 를 지정해야 한다.

<table id="table_id" class="stripe row-border hover nowrap" width="100%">
    <thead>
    <tr>
        <th class="dt-head-center" data-priority="1">학생이름</th>
        <th class="dt-head-center" data-priority="2">나이</th>
        <th class="dt-head-center" data-priority="5">생일</th>
        <th class="dt-head-center" data-priority="4">전화번호</th>
        <th class="dt-head-center" data-priority="3">상태</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="member : ${members}">
        <td class="dt-body-center">
            <button type="button" th:class="${member.delYn} ? 'btn btn-outline-dark' : 'btn btn-secondary'"  th:onclick="'location.href=\''+ @{/signup(id=${member.id})} + '\''">
                <span style="font-weight:500;" th:text="${member.name}" ></span>
            </button>
        </td>
        <td class="dt-body-center" th:text="${#dates.year(#dates.createToday()) } -  ${#numbers.formatInteger(#strings.substring(member.birth,0,4), 0) } + 1 + '세'"></td>
        <td class="dt-body-center" th:text="${#strings.replace(#strings.substring(member.birth,5,10), '-', '/') }"></td>
        <td class="dt-body-center" th:text="${member.parentsTel}"></td>
        <td class="dt-body-center" th:text="${member.delYn} ? '탈퇴' : ''"></td>
    </tr>
    </tbody>
</table>
반응형

이제 jquery 로 datatables 객체를 정의하면 된다. responsive 는 반응형웹을 위한 옵션이고, true 로 하고나면 넓이의 변화에 따라 보여줄 수 있는 컬럼 갯수가 자동 조절된다. lengthChange 가 true 면 페이지당 row 수를 조절할 수 있는 콤보박스가 보이는데, 여기서는 불필요해서 false 로 가렸다. ordering 가 true면 컬럼별로 화살표가 생기는데 올림,내림차순으로 정렬할 수 있게 된다. 근데 디자인상 별로라서 false 로 여기서는 없앴다. 마지막으로 language 는 언어를 지정할 수가 있는데, 한글로 지정하면 된다. 해당 json 은 https://datatables.net/plug-ins/i18n/ 에서 다운받고, 일부 바꾸고 싶은 단어는 직접 바꿔서 쓰면 된다.

$(document).ready( function () {
    $('#table_id').DataTable({
        responsive : true,
        ordering: false,
        language: {
            url: '/js/user/dataTables.ko.json'
        },
        lengthChange: false
    });
} );

 

responsive 설정방법

반응형웹인경우, responsive 옵션을 쓰게 될텐데, 상세한 삽질을 거쳐 정리해본다. 아래 같이 하는 경우, 웹사이트 길이에 따라 컬럼이 자동적으로 숨겨지지만, 맨앞에 + 모양의 컬럼이 생기면서 숨겨진 컬럼을 펼쳐서 볼 수 있게 된다.

responsive : true

 

근데 숨겨진 컬럼들을 보여주는 details 정보를 아예 안나오게 하고 싶으면 아래같이 한다. + 컬럼도 안나오고, 어떤 필드를 클릭해도 child row(숨겨진 필드정보) 가 나오지 않는다.

responsive: {
    details: false
}

 

숨겨진 컬럼들을 나오게는 하고 싶은데, 디폴트로 맨앞 필드를 눌렀을때가 아니라 다른 필드를 클릭했을 때, 보고싶은 거면 아래와 같이 정의한다.

responsive: {
    details: {
        type: 'column',
        target: 1
    }
}

 

참고로, 아래사이트에서 datatables 예시를 구현해놨다. (로그인정보 id : user / pw : password)

 

메인페이지

반갑습니다! 아이들은 자신의 주변 세계를 끊임없이 탐색하며 성장 발달해가는 존재입니다. 이 시기 교육은 다양한 표현 방법 및 사물을 다르게 바라볼 수 있는 힘을 키워주는 중요한 시기이며,

young-wildwood-39551.herokuapp.com

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 28 29 30 31
글 보관함