Skip to content Skip to sidebar Skip to footer

How To Use DataTable In Thymeleaf?

How to use datatable in thymeleaf. i have created a table in which i am creating a div inside of td for all the user present in userInfo list How can i show only one user record as

Solution 1:

The following example shows one way in which you can use Thymeleaf to populate a table, and then use DataTables to display one row at a time (with "previous" and "next" buttons):

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Demo</title>
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
        <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

        <style>
            .dataTables_paginate {
                float: left !important;
            }
        </style>
    </head>

    <body>

        <div style="margin: 20px; width: 150px;">
            <table id="table_id">
                <thead>
                    <tr>
                        <td>Users</td>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="info : ${userInfo}">
                        <td>
                            <p th:text=${info.name}></p>
                            <p th:text=${info.dob}></p>                                     
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#table_id').DataTable({
                    "dom": "tp",
                    "ordering": false,
                    "pagingType": "simple",
                    "lengthMenu": [ 1 ]
                });
            });
        </script>

    </body>
</html>

This creates a very simple display like this, with almost no CSS styling applied:

enter image description here

The Thymeleaf iterator needs to be placed in the tably body's <tr> tag, not in a cell tag.

The HTML table must be defined with both a <thead> and a <tbody> section, for DataTables to be able to use it.

The DataTables options are:

"dom": "tp" - displays only the table (t) and the pagination (p) controls.

"ordering": false - disables column ordering.

"pagingType": "simple" - shows only the "previous" and "next" buttons.

"lengthMenu": [ 1 ] - forces DataTables to show only one row at a time


Post a Comment for "How To Use DataTable In Thymeleaf?"