So Su Team : Web Development Tags : Web Development

Asynchronously loaded localised resource strings for JavaScript.

So Su Team : Web Development Tags : Web Development

With web apps becoming more client heavy, there is a real need for localised resources in JavaScript. I've got all my translations in RESX files. For this particular project we've decided to use requirejs with the i18n plugin to asynchronously load the resource files. This plugin works similarly to the ResourceManager in .NET in that it will fallback to less specific cultures when searching for a translation. Perfect for what we need.

So what's the best way to get those strings from the RESX into JavaScript? Well the i18n plugin expects that the resources are AMDs organised in a specific directory structure. We can simply convert the RESX into the .js files the plugin needs. But we'd have to maintain 2 resource sets. We can do better.

Using MVC, we setup two routes for i18n plugin (one for the root translation file and one for the translated resources). 

            routes.MapRoute(

                name: "I18n",

                url: "Scripts/nls/{culture}/{resource}.js",

                defaults: new { controller = "I18n", action = "Resource" }

            );

           

            routes.MapRoute(

                name: "I18nRoot",

                url: "Scripts/nls/{resource}.js",

                defaults: new { controller = "I18n", action = "Root" }

            );

We point those routes to a MVC controller that enumerates our translations via the ResourceManager and generates the AMD files which we then cache indefinitely. For the i18n plugin it's simply requesting a .js file and doesn't notice any difference. Which is the way it should be. Now we have all our translations in a single location (the RESX) and don't need to worry about the JavaScript. Of course, to get this to work, we need a slight modification to the web.config file to force the request through MVC so that IIS doesn’t intercept our request for a .js file and return 404.  

  <location path="Scripts/nls">

    <system.webServer>

      <handlers>

        <add name="Scriptsi18n" verb="*" path="*.js" type="System.Web.Routing.UrlRoutingHandler" />

      handlers>

    system.webServer>

  location>