applocale.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Application Locale Module
  3. author: tobychui
  4. This module translate the current web application page
  5. to the desired language specific by the browser.
  6. Example Usage:
  7. if (applocale){
  8. //Applocale found. Do localization
  9. applocale.init("../locale/file_explorer.json", function(){
  10. applocale.translate();
  11. //Do other init things on the page
  12. });
  13. }
  14. */
  15. let applocale = {
  16. lang: navigator.language,
  17. localeFile: "",
  18. localData: {},
  19. init: function(localeFile, callback=undefined){
  20. applocale.localeFile = localeFile;
  21. $.ajax({
  22. dataType: "json",
  23. url: localeFile,
  24. success: function(data){
  25. applocale.localData = data;
  26. if (callback != undefined){
  27. callback(data);
  28. }
  29. }
  30. });
  31. },
  32. translate: function(targetLang = ""){
  33. var targetLang = targetLang || applocale.lang;
  34. //Check if the given locale exists
  35. if (applocale.localData.keys[targetLang] == undefined){
  36. console.log("[Applocale] This language is not supported. Using default")
  37. return
  38. }
  39. //Update the page content to fit the localization
  40. let hasTitleLocale = (applocale.localData.keys[targetLang].titles !== undefined);
  41. let hasStringLocale = (applocale.localData.keys[targetLang].strings !== undefined);
  42. let hasPlaceHolderLocale = (applocale.localData.keys[targetLang].placeholder !== undefined);
  43. $("*").each(function(){
  44. if ($(this).attr("title") != undefined && hasTitleLocale){
  45. let targetString = applocale.localData.keys[targetLang].titles[$(this).attr("title")];
  46. if (targetString != undefined){
  47. $(this).attr("title", targetString);
  48. }
  49. }
  50. if ($(this).attr("locale") != undefined && hasStringLocale){
  51. let targetString = applocale.localData.keys[targetLang].strings[$(this).attr("locale")];
  52. if (targetString != undefined){
  53. $(this).html(targetString);
  54. }
  55. }
  56. if ($(this).attr("placeholder") != undefined && hasPlaceHolderLocale){
  57. let targetString = applocale.localData.keys[targetLang].placeholder[$(this).attr("placeholder")];
  58. if (targetString != undefined){
  59. $(this).attr("placeholder",targetString);
  60. }
  61. }
  62. })
  63. },
  64. getString: function(key, original, type="strings"){
  65. var targetLang = applocale.lang;
  66. if (applocale.localData.keys[targetLang] == undefined){
  67. return original;
  68. }
  69. let targetString = applocale.localData.keys[targetLang].strings[key];
  70. if (targetString != undefined){
  71. return targetString
  72. }else{
  73. return original
  74. }
  75. }
  76. }