Localize Strings in Javascript

前端 未结 12 1308
长发绾君心
长发绾君心 2020-11-28 05:52

I\'m currently using .resx files to manage my server side resources for .NET.

the application that I am dealing with also allows developers to plugin Ja

相关标签:
12条回答
  • 2020-11-28 05:56

    A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using JSON, you could create an object for each string to be localized like this:

    var localizedStrings={
        confirmMessage:{
            'en/US':'Are you sure?',
            'fr/FR':'Est-ce que vous êtes certain?',
            ...
        },
    
        ...
    }
    

    Then you could get the locale version of each string like this:

    var locale='en/US';
    var confirm=localizedStrings['confirmMessage'][locale];
    
    0 讨论(0)
  • 2020-11-28 05:56

    There's a library for localizing JavaScript applications: https://github.com/wikimedia/jquery.i18n

    It can do parameter replacement, supports gender (clever he/she handling), number (clever plural handling, including languages that have more than one plural form), and custom grammar rules that some languages need.

    The strings are stored in JSON files.

    The only requirement is jQuery.

    0 讨论(0)
  • 2020-11-28 05:58

    JSGettext does an excellent job -- dynamic loading of GNU Gettext .po files using pretty much any language on the backend. Google for "Dynamic Javascript localization with Gettext and PHP" to find a walkthrough for JSGettext with PHP (I'd post the link, but this silly site won't let me, sigh...)

    Edit: this should be the link

    0 讨论(0)
  • 2020-11-28 06:03

    I would use an object/array notation:

    var phrases={};
    phrases['fatalError'] ='On no!';
    

    Then you can just swap the JS file, or use an Ajax call to redefine your phrase list.

    0 讨论(0)
  • 2020-11-28 06:04

    I did the following to localize JavaScript for a mobile app running HTML5:

    1.Created a set of resource files for each language calling them like "en.js" for English. Each contained the different strings the app as follows:

    
            var localString = {
            appName: "your app name",
            message1: "blah blah"
          };
    

    2.Used Lazyload to load the proper resource file based on the locale language of the app: https://github.com/rgrove/lazyload

    3.Pass the language code via a Query String (As I am launching the html file from Android using PhoneGap)

    4.Then I wrote the following code to load dynamically the proper resource file:

    
    var lang = getQueryString("language");
    localization(lang);
    function localization(languageCode) {
        try {
            var defaultLang = "en";
            var resourcesFolder = "values/";
            if(!languageCode || languageCode.length == 0)
                languageCode = defaultLang;
            // var LOCALIZATION = null;
            LazyLoad.js(resourcesFolder + languageCode + ".js", function() {
                if( typeof LOCALIZATION == 'undefined') {
                    LazyLoad.js(resourcesFolder + defaultLang + ".js", function() {
                        for(var propertyName in LOCALIZATION) {
                            $("#" + propertyName).html(LOCALIZATION[propertyName]);
                        }
                    });
                } else {
                    for(var propertyName in LOCALIZATION) {
                        $("#" + propertyName).html(LOCALIZATION[propertyName]);
                    }
                }
            });
        } catch (e) {
            errorEvent(e);
        }
    }
    function getQueryString(name)
    {
      name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
      var regexS = "[\\?&]" + name + "=([^&#]*)";
      var regex = new RegExp(regexS);
      var results = regex.exec(window.location.href);
      if(results == null)
        return "";
      else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
    }
    

    5.From the html file I refer to the strings as follows:

    
        span id="appName"
    
    0 讨论(0)
  • 2020-11-28 06:05

    With a satellite assembly (instead of a resx file) you can enumerate all strings on the server, where you know the language, thus generating a Javascript object with only the strings for the correct language.

    Something like this works for us (VB.NET code):

    Dim rm As New ResourceManager([resource name], [your assembly])
    Dim rs As ResourceSet = 
        rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
    For Each kvp As DictionaryEntry In rs
        [Write out kvp.Key and kvp.Value]
    Next
    

    However, we haven't found a way to do this for .resx files yet, sadly.

    0 讨论(0)
提交回复
热议问题