Search code examples
datatablesrails-i18n

I18n translations not rendering in Datatable initializations?


I am trying to apply translations to a jquery dataTable. ie.

myTable.DataTable({
              language: {
                paginate: {
                   next: (I18n.t('filters.paginate.next')),
                   previous: (I18n.t('filters.paginate.previous'))
                }
              }
            });

When I run:

I18n.locale //=>en (even when the locale is changed)

Below, you see the I18n json shows two different locales for the same value, only is picking up one in brackets, even though they are the same attribute ?

enter image description here


Solution

  • After some time I have found the reason for the issue was that the function I was using to initialize my dataTables was IIFE (function() { })();, and was being processed before $(document).ready, and the correct I18n locale would not update for my translations in time. So I used a regex on the URL query string with a function called in the IIFE, and set the I18n.locale to the found value:

    function QueryString(item){
       var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*) 
       (\&?)","i"));
       return svalue ? svalue[1] : svalue;
    }
    
    (function() {
    I18n.locale = QueryString('locale');
    //initialized tables and added translations
    .... })();