Posted By

Pjotor on 08/12/14


Tagged

jquery i18n localization


Versions (?)

i18n Deserializer


 / Published in: JavaScript
 

URL: http://pjotor.com

Deserializer for i18n objects.

This will take all the child elements in the .i18n element and populate the localization object with the textual content in the element and extend the parent object with dot notation key based on the class of the element.

Eg. Translated text

would add the key(s) localization.demo.textString and set the value for the key to "Translated text"

Use {i18n()} to populate internationalization.

@return undefined

  1. // Deserializer for i18n objects.
  2. //
  3. // This will take all the child elements in the .i18n element and populate the localization object
  4. // with the textual content in the element and extend the parent object with dot notation key based
  5. // on the class of the element.
  6. //
  7. // Eg. <div class="i18n">
  8. // <div class="demo textString">Translated text</div>
  9. // </div>
  10. //
  11. // would add the key(s) localization.demo.textString
  12. // and set the value for the key to "Translated text"
  13. //
  14. // Use {i18n()} to populate internationalization.
  15. //
  16. // @return undefined
  17.  
  18. var localization = {};
  19.  
  20. function i18n(){ //Sets up the i18n object
  21. var i18n = {};
  22. $(".i18n").children().each(function(){
  23. if($(this).attr("class")) {
  24. var val = $(this).text();
  25. var serialized = [$(this).attr("class").replace(/\s/gi,".")].join(".");
  26.  
  27. if (serialized.indexOf('.') > -1) {
  28. var attrs = serialized.split('.');
  29. var tx = i18n;
  30.  
  31. for (var i = 0; i < attrs.length - 1; i++) {
  32. if (i18n[attrs[i]] == undefined)
  33. i18n[attrs[i]] = {};
  34. tx = i18n[attrs[i]];
  35. }
  36.  
  37. tx[attrs[attrs.length - 1]] = val;
  38.  
  39. } else {
  40.  
  41. if (i18n[serialized] != null) {
  42. if (!i18n[serialized].push) {
  43. i18n[serialized] = [i18n[serialized]];
  44. }
  45.  
  46. i18n[serialized].push(val);
  47. } else {
  48. i18n[serialized] = val;
  49. }
  50.  
  51. }
  52. }
  53. });
  54. $.extend(localization,i18n);
  55. }

Report this snippet  

You need to login to post a comment.