Magento2 RequireJS – How to Use Datatable JS Library in Magento 2

magento-2.1magento2requirejs

what's the best way to use the datatable js library in my template file ?
I tried like this but it doesn't work :

layout file:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <head>
          <css src="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" src_type="url"/>
          <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" src_type="url"/>
     </head>
    <body>
        <referenceContainer name="content">
            <block
                template="Fmj_Portefeuill::portefeuille.phtml"
                class="Fmj\Portefeuill\Block\portefeuille"
                name="FMJ_portefeuill"/>
        </referenceContainer>
    </body>
</page>

template file :

<table id="portefeuilleTable"> ... </table>
<script>
    require([
        'jquery'
    ], function($){
        $(function(){
                $('#portefeuilleTable').DataTable();
            });
        });

</script>

Best Answer

Remove <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" src_type="url"/> from xml.

  1. Copy jquery.dataTables.min.js inside VendorName/ModuleName/view/frontend/web/js. So location of the file is: VendorName/ModuleName/view/frontend/web/js/jquery.dataTables.min.js

  2. Inside phtml template add following code


<script>
    require([
        'jquery',
        'VendorName_ModuleName/js/jquery.dataTables.min'
    ], function($, $t){
        $(document).ready(function() {
            $('#example').DataTable();
        } );
    })
</script>

Clear cache.