¿Complemento de localización i18n para Jquery Mobile?

is any i18n localization plugin for Jquery Mobile? I searched a lot of time, but i18n translations plugins for Jquery not working correctly on JQM. For example in a href..many thanks.

¿Nadie lo sabe?

preguntado el 31 de enero de 12 a las 16:01

5 Respuestas

I have had the same problem, and I resolved the problem simply by using the Jquery Extend function.

Say you define your language resources as follows:

1) Create a resource file with the default localization, presumably defined in English. Let's call it resources.default.js

var MyApp = MyApp || {};

MyApp.resources = {
    One: "One",
    Two: "Two",
    Three:"Three"    
}

2) Define your localized resources in independent files, let's say Spanish. Call it resources.es.js

var localizedResources = {
    One: "Uno",
    Two: "Dos",
    Three:"Tres"    
}

3) On your server logic, decide that you need to include only the default translations in case of English, or if you need any other language do an include.

<script src="resources.es.js"> </script> 

4) Create your web page, and add scripts to handle your inclusion of the resources, per step 3.

<html>
<head>
</head>
<body>

​<h1>Welcome to my App</h1>
<p>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​Welcome to this test app</p>

<button>Click me</button>​



<script src="resources.default.js"> </script> 


// The server decided we needed Spanish translations.
<script src="resources.es.js"> </script> 


<script type="text/javascript">
    //Extend the translations into the resources object.

    $.extend(MyApp.resources, localizedResources);

    $(window).ready(function(){
        $('button').click(function(){
            alert(MyApp.resources.One);    
        });    
    });

</script>  
</body>

This should work for you. ​ EDIT: See it in action here: http://jsfiddle.net/agarcian/rrDv3/1/

Respondido 16 Feb 12, 13:02

It looks like good solution, but i cannot access to localizedResources, only in default translation (english) works. I used translation switch in document ready: $(document).ready(function () { $.extend(MyApp.resources, localizedResources); }); And definition in head after all JS scripts: <script type="text/javascript" src="resources.default.js"></script> <script type="text/javascript" src="resources.es.js"></script> - redrom

the script tag to the resources.default.js? could i place it in the head, or it must be in the body? - Michael Unterthurner

You can place it anywhere in the document that is allowed. This is simply a script tag so it follows the html rules for the tag. - agarciano

I'm using the following script for my projects. It allows you to change the language "at runtime", without reloading the page. The script is "autorun", just add it at the end of the html page. It could have some bugs ;)

    // AutoStar!
// Grab the parameters from my url, and initialize myself! FUGOOOOO
(function __lang_init_wrapper()
{
    var scriptSrc = $('script[src*=Lang]').attr('src');
    var myParams = parseParams(scriptSrc);

    new Lang(myParams.language.toUpperCase(), true);

})();

/**
 * Thanks to: http://wowmotty.blogspot.com/2010/04/get-parameters-from-your-script-tag.html
 * @param n
 * @param s
 */
function gup(n,s){
n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
return (p===null) ? "" : p[1];
}

/**
 *
 * @param language The language to use
 * @param replaceText If true, replace all the occurency marked with placemark {lang=<key>}
 */
function Lang(language, replaceText)
{

    var Languages =
    {
        ENG:
        {
            ok: 'ok'
            ,yes: 'yes'
            ,no: 'no'
            ,unknown_user: 'Unknown user'
            ,too_soon: "It's not time, yet..!"
        }

        ,ITA:
        {
            yes: 'si'
            ,unknown_user: 'Utente sconosciuto'
            ,too_soon: "Pazienta ancora un po'..!"
        }
    }

    // GENERAL SETTINGS

    var LANG_CURRENT = language;

    var LANG_DEFAULT = 'ENG';

    /**
     * All the html elements with this attributes are translated on the fly
     */
    var LANG_ATTRIBUTE_NAME = "uilang"


    /**
     * key è la chiave da usare nell'oggetto LANG
     * @param key
     */
    this.get = function(key)
    {
        return Languages[LANG_CURRENT][key] || Languages[LANG_DEFAULT][key];
    }

    /**
     * Cerco tutti gli elementi che hanno una certa classe
     */
    this.searchAndReplace = function()
    {
        var me = this;
        var divs = $('*[' + LANG_ATTRIBUTE_NAME + ']');

        $.each(divs,function(indx,item)
        {
            item = $(item);
            item.text(me.get(item.attr(LANG_ATTRIBUTE_NAME)));
        });

    }

    this.setLanguage = function(language, replaceText)
    {
        LANG_CURRENT = language;
        if(replaceText){
            this.searchAndReplace();
        }
    }

    if(replaceText){
        this.searchAndReplace();
    }

    // Returns a localized instance of language
    Lang = {
        get: this.get
        ,searchAndReplace: this.searchAndReplace
        ,setLanguage: this.setLanguage
    };
}

TO use it, just "mark" an html element

<h1 uilang="unknown_user"></h1>

o llame al

Lang.get('unknown_user')

to get the localized string

To initialize, call the "constructor"

new Lang("ITA", true);

To use it specifyng a language,

<script type="text/javascript" src="js/Lang.js?language=ita"></script>

Respondido 14 Feb 12, 18:02

You might also try a PhoneGap plug-in in case you are writing a Hybrid Mobile app. Here's the link: https://github.com/ljbotero/phonegap-plugins/tree/master/Android/Localization

Respondido 10 Jul 12, 23:07

Estoy intentando con i18siguiente, which works ok for most widgets after the lateste release (which allows to set a target of where the text should go).

However I'm still at a loss how to translate dynamically generated things like the table popup.

Other than that it's working really well.

A continuación se explica cómo configurarlo:

 lang : function (page) {
        var update_language,
          translate = function (page) {
          page.find('.t').i18n();
          },
          set_lang = function (language) {
            var set_icon;
            switch (language) {
              case "de-DE":
                set_icon = "DE";
              break;
              case "fr-FR":
                set_icon = "FR";
              break;
              default:
                set_icon = "EN";
              break;
            }
            $(".setIcon").parent(".ui-btn").find(".ui-icon")
              .removeClass().addClass('ui-icon ui-shadow ui-icon-lang '+set_icon);
          }
        if (fauna.i18set === undefined) {
          i18n.init({
            lng: 'en-EN',
            load: 'current',
            detectLngQS: 'lang',
            fallbackLng: false,
            resGetPath: '../lang/__lng__/__ns__.json',
            ns: 'gen',
              debug: true,
            // , useLocalStorage: true
            // , localStorageExpirationTime: 86400000 // in ms, default 1 week
          }, function () {
            translate(page);
            set_lang(i18n.lng());
          });
          fauna.i18set = true;
        } else {
          update_language = $.mobile.path.parseUrl( window.location.href )
            .hash.replace( /.*lang=/, "" );
          if (update_language !== "") {
            i18n.setLng(update_language, function() {
              translate(page);
              set_lang(i18n.lng());
            });
          } else {
            translate(page);
          }
        }
      }

Entonces estoy usando un .t class to label elements for translation (lookup class is faster than data-attributes).

I'm calling the above on pagebeforeshow which also seems to handle everything nicely.

Sidenote: Just noticed the update_language will fail if pushstate is disabled. Need a better regex for this.

Respondido 18 Feb 13, 21:02

You can try the framework HTMLed.js. Its pretty much easier. Checkout the framework.

aquí es la enlace

contestado el 23 de mayo de 13 a las 23:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.