Reputation: 3348
I'm working with Datatables.js in different human languages. I'm using the language plugins provided by Datatables and they work fine. However, I would like to overwrite a few of the translations with my own translations.
How can I do this in the best way?
Here's my code:
function getLanguage() {
var $langMap = {
en: 'English',
es: 'Spanish'
};
var $lang = $('html').attr('lang');
return '//cdn.datatables.net/plug-ins/1.10.13/i18n/' + $langMap[$lang] + '.json';
}
// Build Datatable
$('#example').DataTable({
language: {
url: getLanguage() // works perfectly, but I need to overwrite with a few custom text options
}
});
Say, I want to owerwrite these language options:
en: {
// Overwrite defaults with this string
"lengthMenu": "Display _MENU_ records per page - custom test",
},
es: {
// Overwrite Spanish defaults with this string
"lengthMenu": "Mostrar _MENU_ registros - algo muy especial...",
}
Ref: Datatables.js language options.
Upvotes: 0
Views: 2996
Reputation: 85538
You could expand your langMap
to hold the modifications you want to add to the language struct :
var langMap = {
en: {
path: 'English',
mods: {
sLengthMenu: "Display _MENU_ records per page - custom test"
}
},
es: {
path: 'Spanish',
mods: {
sLengthMenu: "Mostrar _MENU_ registros - algo muy especial..."
}
}
};
Notice I am using hungarian notation, sLengthMenu
instead of lengthMenu
. This is due to the fact that the language files still is using this format. Then load the language object through a synchronous AJAX request, modify with the mods
and return
function getLanguage() {
var lang = $('html').attr('lang');
var path = '//cdn.datatables.net/plug-ins/1.10.13/i18n/';
var result = null;
$.ajax({
async: false,
url: path + langMap[lang].path + '.json',
success: function(obj) {
result = $.extend({}, obj, langMap[lang].mods)
}
})
return result
}
// Build Datatable
$('#example').DataTable({
language: getLanguage()
});
demo -> http://jsfiddle.net/v84wjLqe/ (with hardcoded es
just for test)
Note: Instead of using async: false
you could consider using a promise, jQuery deferred, q or one of the promise polyfills. But this is beyond the question.
Upvotes: 1