how to change language for DataTable

前端 未结 11 1770
灰色年华
灰色年华 2020-12-14 15:11

I store, in a session variable, which language does user wants to translate but I don\'t know to pass it DataTables

I found this explanation on the datatables websit

11条回答
  •  青春惊慌失措
    2020-12-14 16:06

    It is indeed

    language: {
     url: '//URL_TO_CDN'
    }
    

    The problem is not all of the DataTables (As of this writing) are valid JSON. The Traditional Chinese file for instance is one of them.

    To get around this I wrote the following code in JavaScript:

      var dataTableLanguages = {
        'es': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json',
        'fr': '//cdn.datatables.net/plug-ins/1.10.21/i18n/French.json',
        'ar': '//cdn.datatables.net/plug-ins/1.10.21/i18n/Arabic.json',
        'zh-TW': {
          "processing": "處理中...",
          "loadingRecords": "載入中...",
          "lengthMenu": "顯示 _MENU_ 項結果",
          "zeroRecords": "沒有符合的結果",
          "info": "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
          "infoEmpty": "顯示第 0 至 0 項結果,共 0 項",
          "infoFiltered": "(從 _MAX_ 項結果中過濾)",
          "infoPostFix": "",
          "search": "搜尋:",
          "paginate": {
            "first": "第一頁",
            "previous": "上一頁",
            "next": "下一頁",
            "last": "最後一頁"
          },
          "aria": {
            "sortAscending": ": 升冪排列",
            "sortDescending": ": 降冪排列"
          }
        }
      };
      var language = dataTableLanguages[$('html').attr('lang')];
    
      var opts = {...};
      
      if (language) {
        if (typeof language === 'string') {
           opts.language = {
             url: language
           };
        } else {
           opts.language = language;
        }
      }
    

    Now use the opts as option object for data table like

    $('#list-table').DataTable(opts)
    

提交回复
热议问题