Localize Strings in Javascript

51,220

Solution 1

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];

Solution 2

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] );

Solution 3

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);

Solution 4

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.

Solution 5

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.

Share:
51,220

Related videos on Youtube

SaaS Developer
Author by

SaaS Developer

Software developer\Entreprenuer who focuses on web-based Software as a Service solutions.

Updated on September 21, 2020

Comments

  • SaaS Developer
    SaaS Developer over 3 years

    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 JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings?

    Ideally, I would like to store the strings in the .resx files to keep them with the rest of the localized resources.

    I'm open to suggestions.

  • AnthonyWJones
    AnthonyWJones over 15 years
    The problem with this approach is that you load all strings for all languages. However its likely the server will know either through browser provided clues or through user preferences what language is needed. Sending a single language file would be better.
  • Niraj
    Niraj over 15 years
    Note that this isn't correct. phrases will be an Array, but you're just setting one of its properties to a string (eg phrases.fatalError = 'Oh no'; is equivalent to your second line). Use object literals for cleanliness instead.
  • Ruan Mendes
    Ruan Mendes over 12 years
    Since I write OO JS, each object defines default English strings that it uses on the prototype. If I need another language, I just load another file the modifies the prototype strings. That way I don't need to load all the strings for one language at once (they're dynamically loaded). The drawback is that you may need to repeat some strings across objects.
  • Ruan Mendes
    Ruan Mendes over 12 years
    Just cause it's MS, it's bad? FAILED attempt at being funny! That is the most widely used way. If this is the worst way, you need to at least explain why!
  • brunosp86
    brunosp86 over 12 years
    @Juan Attempt to be funny? My guesses are the way you're localizing your strings in js is exactly the MSDN way, a.k.a "CPP - Copy and Paste Programming" and couldn't bear someone criticizing it. "The most widely used way" is to violate DRY principle according to your statement, but you probably don't see it as a code smell.
  • Ruan Mendes
    Ruan Mendes over 12 years
    How is that a violation of DRY? Even if your argument is true, the answer is still weak since it doesn't explain anything.
  • Andrew Dunkman
    Andrew Dunkman over 12 years
    IMHO, this is one of the most DRY solutions. The strings are only in one file, in one place—and that file is referenced by anywhere that needs to display strings.
  • Andrew Theken
    Andrew Theken over 12 years
    simply inverting the order 'localizedStrings[culture][key]' resolves the issue about loading multiple cultures.. it could also allow the 'neutral' culture to be used as the prototype for all the others (providing a seamless fallback when a culture doesn't define a particular key)
  • Josh Earl
    Josh Earl about 12 years
    jQuery UI also uses the "MSDN way" that you're mocking. Love how everything Microsoft does is "wrong" to some people.
  • shailbenq
    shailbenq over 11 years
    Can you explain what exactly this block of code is doing : 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]); } }
  • Jochen van Wylick
    Jochen van Wylick over 11 years
    I'm using T4 to generate exactly the code suggested above.
  • Julian
    Julian over 11 years
    The problem is that they are advocating replicating the logic (verbatim) for every single language you want to support. They are also suggesting mixing your string resources with your code. Neither is a good idea. Jquery.i18n mentioned above does not do this. They separate data (string resources) from code, and similarly keep 1 copy of your logic, again separate from data.
  • Tracker1
    Tracker1 over 10 years
    I believe they are recommending you have a script include, a separate file for each language.. with one exports (which is an object with key/value pairs) for the specific language.. and include that separately from your code/logic.. this is precisely what jQuery.i18n uses.
  • João Antunes
    João Antunes over 6 years
    guys guys, chill, the way that is proposed on MSDN isn't as good because if you actually use a .resx file you will need to repeat it in JS. so far the DRYies way is: stackoverflow.com/a/14782225/1930376