Localize Strings in Javascript

前端 未结 12 1309
长发绾君心
长发绾君心 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 06:05

    The MSDN way of doing it, basically is:

    You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.

    I can't tell you the best solution for your question, but IMHO this is the worst way of doing it. At least now you know how NOT to do it.

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

    After Googling a lot and not satisfied with the majority of solutions presented, I have just found an amazing/generic solution that uses T4 templates. The complete post by Jochen van Wylick you can read here:

    Using T4 for localizing JavaScript resources based on .resx files

    Main advantages are:

    1. Having only 1 place where resources are managed ( namely the .resx files )
    2. Support for multiple cultures
    3. Leverage IntelliSense - allow for code completion

    Disadvantages:

    The shortcomings of this solution are of course that the size of the .js file might become quite large. However, since it's cached by the browser, we don't consider this a problem for our application. However - this caching can also result in the browser not finding the resource called from code.


    How this works?

    Basically he defined a T4 template that points to your .resx files. With some C# code he traverses each and every resource string and add it to JavaScript pure key value properties that then are output in a single JavaScript file called Resources.js (you can tweak the names if you wish).


    T4 template [ change accordingly to point to your .resx files location ]

    <#@ template language="C#" debug="false" hostspecific="true"#>
    <#@ assembly name="System.Windows.Forms" #>
    <#@ import namespace="System.Resources" #>
    <#@ import namespace="System.Collections" #>
    <#@ import namespace="System.IO" #>
    <#@ output extension=".js"#>
    <#
     var path = Path.GetDirectoryName(Host.TemplateFile) + "/../App_GlobalResources/";
     var resourceNames = new string[1]
     {
      "Common"
     };
    
    #>
    /**
    * Resources
    * ---------
    * This file is auto-generated by a tool
    * 2012 Jochen van Wylick
    **/
    var Resources = {
     <# foreach (var name in resourceNames) { #>
     <#=name #>: {},
     <# } #>
    };
    <# foreach (var name in resourceNames) {
     var nlFile = Host.ResolvePath(path + name + ".nl.resx" );
     var enFile = Host.ResolvePath(path + name + ".resx" );
     ResXResourceSet nlResxSet = new ResXResourceSet(nlFile);
     ResXResourceSet enResxSet = new ResXResourceSet(enFile);
    #>
    
    <# foreach (DictionaryEntry item in nlResxSet) { #>
    Resources.<#=name#>.<#=item.Key.ToString()#> = {
     'nl-NL': '<#= ("" + item.Value).Replace("\r\n", string.Empty).Replace("'","\\'")#>',
     'en-GB': '<#= ("" + enResxSet.GetString(item.Key.ToString())).Replace("\r\n", string.Empty).Replace("'","\\'")#>'
     };
    <# } #>
    <# } #>
    

    In the Form/View side

    To have the correct translation picked up, add this in your master if you're using WebForms:

    <script type="text/javascript">
    
        var locale = '<%= System.Threading.Thread.CurrentThread.CurrentCulture.Name %>';
    
    </script>
    
    <script type="text/javascript" src="/Scripts/Resources.js"></script>
    

    If you're using ASP.NET MVC (like me), you can do this:

    <script type="text/javascript">
    
        // Setting Locale that will be used by JavaScript translations
        var locale = $("meta[name='accept-language']").attr("content");
    
    </script>
    
    <script type="text/javascript" src="/Scripts/Resources.js"></script>
    

    The MetaAcceptLanguage helper I got from this awesome post by Scott Hanselman:

    Globalization, Internationalization and Localization in ASP.NET MVC 3, JavaScript and jQuery - Part 1

    public static IHtmlString MetaAcceptLanguage<T>(this HtmlHelper<T> html)
    {
         var acceptLanguage =
             HttpUtility.HtmlAttributeEncode(
                         Thread.CurrentThread.CurrentUICulture.ToString());
    
          return new HtmlString(
          String.Format("<meta name=\"{0}\" content=\"{1}\">", "accept-language",
                        acceptLanguage));
     }
    

    Use it

    var msg = Resources.Common.Greeting[locale];
    alert(msg);
    
    0 讨论(0)
  • 2020-11-28 06:09

    Well, I think that you can consider this. English-Spanish example:

    Write 2 Js Scripts, like that:

    en-GB.js
    lang = {
        date_message: 'The start date is incorrect',
        ...
    };
    es-ES.js
    lang = {
        date_message: 'Fecha de inicio incorrecta',
        ...
    };
    

    Server side - code behind:

    Protected Overrides Sub InitializeCulture()
        Dim sLang As String 
        sLang = "es-ES" 
    
        Me.Culture = sLang
        Me.UICulture = sLang
        Page.ClientScript.RegisterClientScriptInclude(sLang & ".js", "../Scripts/" & sLang & ".js")
    
        MyBase.InitializeCulture()
    End Sub
    

    Where sLang could be "en-GB", you know, depending on current user's selection ...

    Javascript calls:

    alert (lang.date_message);
    

    And it works, very easy, I think.

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

    Inspired by SproutCore You can set properties of strings:

    'Hello'.fr = 'Bonjour';
    'Hello'.es = 'Hola';
    

    and then simply spit out the proper localization based on your locale:

    var locale = 'en';
    alert( message[locale] );
    
    0 讨论(0)
  • 2020-11-28 06:17

    We use MVC and have simply created a controller action to return a localized string. We maintain the user's culture in session and set the thread culture before any call to retrieve a language string, AJAX or otherwise. This means we always return a localized string.

    I'll admit, it isn't the most efficient method but getting a localised string in javascript is seldom required as most localization is done in our partial views.

    Global.asax.cs

    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
        {
            // Set the current thread's culture
            var culture = (CultureInfo)Session["CultureInfo"];
            if (culture != null)
            {
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = culture;
            }
        }
    }
    

    Controller Action

    public string GetString(string key)
    {
        return Language.ResourceManager.GetString(key);
    }
    

    Javascript

    /*
        Retrieve a localized language string given a lookup key.
        Example use:
          var str = language.getString('MyString');
    */
    var language = new function () {
        this.getString = function (key) {
            var retVal = '';
            $.ajax({
                url: rootUrl + 'Language/GetString?key=' + key,
                async: false,
                success: function (results) {
                    retVal = results;
                }
            });
            return retVal;
        }
    };
    
    0 讨论(0)
  • 2020-11-28 06:19

    Expanding on diodeus.myopenid.com's answer: Have your code write out a file containing a JS array with all the required strings, then load the appropriate file/script before the other JS code.

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