JavaScript internationalization and localization


The official jQuery Globalization plugin is at https://github.com/jquery/globalize, it's for the globalization of string, date, and number formatting and parsing.
Cultures: English, Arabic, Bulgarian, Catalan, Chinese(Simplified), Chinese (Traditional) Legacy, Czech, Danish,  German, Greek, Spanish, Finnish, French, Hebrew, Hungarian, Icelandic, Italian, Japanese, Korean, Dutch, Norwegian, Polish, Portuguese, Romansh, Romanian, Russian, Croatian, Slovak, Albanian, Swedish, Thai, Turkish, Urdu, Indonesian, Ukrainian, Belarusian, Slovenian, Estonian, Latvian, Lithuanian, Tajik, Persian, Vietnamese, Armenian, Azeri, Basque, Upper Sorbian, Macedonian (FYROM), Setswana, isiXhosa, isiZulu, Afrikaans, Georgian, Faroese, Hindi, Maltese, Sami (Northern), Irish, Malay, Kazakh, Kyrgyz, Kiswahili, Turkmen, Uzbek, Tatar, Bengali, Punjabi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Assamese, Marathi, Sanskrit, Mongolian, Tibetan, Welsh, Khmer, Lao, Galician, Konkani, Syriac, Sinhala, Inuktitut, Amharic, Tamazight, Nepali, Frisian, Pashto, Filipino, Divehi, ...

http://www.ibm.com/developerworks/opensource/library/os-jquerynewpart1/index.html
http://wiki.jqueryui.com/w/page/39118647/Globalize
http://weblogs.asp.net/scottgu/jquery-globalization-plugin-from-microsoft
http://wijmo.com/docs/wijmo/#Localization.html

Using Language Tags


The jQuery Globalization plugin uses the language tags defined in the RFC 4646 and RFC 5646 standards to identity cultures (see http://tools.ietf.org/html/rfc5646).  
 The preferCulture() method enables you to set the default culture used by the jQuery Globalization plugin methods. Notice that the preferCulture() method accepts a language tag. The method will find the closest culture that matches the language tag.
Globalize.locale( "zh-cmn" );
 
$.preferCulture("de-DE")
// Remember, this only works if you include the globalize.js file!
// And, you HAVE to include the globalize.cultures.js file OR
// each individual culture's JS file

// You can set the culture directly by referencing its name
Globalize.culture = Globalize.cultures.de;

// You can set the culture directly by referencing it from
// the Cultures array
Globalize.culture = Globalize.cultures["de-DE"];


 //Populate select list
var select = $("#selectCulture").get(0);
select.options.length=0;
$.each($.cultures,
       function(){
          select.options[select.options.length]=new Option(this.englisthName,this.name);     
        }
);
$("#selectCulture").change(function(){
  //Set culture from select list
  $.preferCulture(this.value);
  //Format dates
  $("span[data-date]").html(function(){
     var dateString=$(this).attr("data-date");
     var dateValue=$.parseDate(dateString, "d","en-US");
    return $.format(dateValuek "D");
  }
);
            // Destroy and create datepicker
            $("#picker").datepicker("destroy").datepicker({
                changeMonth: true,
                changeYear: true
            });
 The following jQuery code executes whenever a user selects a new language from the dropdown list. The code checks whether the globalization file associated with the selected language has already been loaded. If the globalization file has not been loaded then the globalization file is loaded dynamically by taking advantage of the jQuery $.getScript() method.
$("#selectCuture").change(function(){
 var selectedCulture=this.value;
 if($.cultures[selectedCulture]){
   globalizePage(selectedCulture)
  }else{
   var globPath="scripts/globinfo/jQuery.glob."+selectedCulture+".js";
   $.getScript(globPath,function(){
     globalizePage(selectedCulture)
    });
  }
});

Detecting country with servlet
Depending on what you need this information for, it might or might not be straightforward. If end user's web browser is configured correctly, it will give you the hint of end user's preferred location - that would be the part of Locale. If you only need that information to decide on which localized page to load, that would be probably the best option. Of course if Locale object is not specific (country-less) you may want to assign "default" country for each supported non-specific Locale. In both cases, you should provide end user with some means of switching country (i.e. through "Other countries" combo box). The list could be obtained like this:
public String[] getOtherCountries() {
    Set<String> countries = new HashSet<String>();
    Set<Object> keys = supportedLanguages.keySet();
    for (Object key : keys) {
        Locale other = (Locale) supportedLanguages.get(key);
        if (other != requestLocale) {
            countries.add(other.getDisplayCountry(requestLocale));
        }
    }

    return countries.toArray(new String[0]);
}
Web browsers tend to send AcceptLanguage header and Java Servlet API is 
so nice to actually convert it contents to Locale object(s).  
public class LousyServlet extends HttpServlet {
    private Properties supportedLanguages;
    private Locale requestLocale = (Locale) supportedLanguages.get("DEFAULT");

    public LousyServlet() {
        supportedLanguages = new Properties();
        // Just for demonstration of the concept
        // you would probably load it from i.e. XML
        supportedLanguages.put("DEFAULT", Locale.US);
        // example mapping of "de" to "de_DE"
        supportedLanguages.put("de-DEFAULT", Locale.GERMANY);
        supportedLanguages.put("de_AT", new Locale("de", "AT"));
        supportedLanguages.put("de_CH", new Locale("de", "CH"));
        supportedLanguages.put("ja_JP", Locale.JAPAN);
    }
...  http://stackoverflow.com/questions/5988656/automatically-selecting-country-and-language-for-user-in-java-servlet
 

Dynamic globalization

Listing 7. Java internationalization code
<%
    // the user's preferred language is stored in the Header, and the Accept-Language
    // field
    // For example, in my Firefox browser, it shows 
    // en-us,en;q=0.5
    // This means my primary Culture is "en-us" which has a q=1.0
    // My backup Culture is "en" neutral, which has a q=0.5
    // q values are used to rank the cultures and are a system
    // for safe fail-over
    String header = request.getHeader("Accept-Language");
    
    // Split each language into separate locales
    String[] locales = header.split(",");

    // load the globalize.js file, which must always
    // be loaded to use the Globalize plugin
    out.println("<script src=\"globalize.js\"
                type=\"text/javascript\"></script>");

    // loop through each locale, and load the appropriate Globalize
    // plugin file.
    // for example, since I have 2 locales, it will load the
    // globalize.culture.en-US.js file and the
    // globalize.culture.en.js file
    for (int i=0; i<locales.length; i++)
    {
        int end = (locales[i].indexOf(";") == -1) ? locales[i].length() : 
          locales[i].indexOf(";");
        String locale = locales[i].substring(0,end);
        out.println("<script src=\"cultures/globalize.culture." +
                    locale + 
                    ".js\" type=\"text/javascript\"></script>");
    }

    // Finally, call culture() with the Accept-Language
    // The Globalize plugin accepts the String directly from
    // the Header, and deals with the q values appropriately,
    // even failing over safely on its own
    out.println("<script>$(document).ready(function(){Globalize.culture(\"" +
               header + 
               "\");});</script>");
%>
Listing 8. PHP internationalization code
// Here's the same thing in PHP
<?
$accept_language = $_SERVER["HTTP_ACCEPT_LANGUAGE"];

$languages = explode(",", $accept_language);

echo "<script src=\"globalize.js\" type=\"text/javascript\"></script>";

for each ($languages as $language) {
        $locale = explode(";", $language);

        echo "<script src=\"cultures/globalize.culture.".$locale[0].".js\"
          type=\"text/javascript\"></script>";
}

echo '<script>$(document).ready(function(){Globalize.culture
          ("'.$accept_language.'");});</script>';
?>

 

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE