Localize text in JavaScript files in ASP.NET
Just about every web project I’ve been involved in have, at one time or the other, needed to present some text to the visitor through JavaScript. It could be in an alert box or some other way and the problem has always been to localize that text into different languages using resource files or satellite assemblies.
There are many ways of localizing the keys, but most of them involve writing out variables on a page with the localized text and then let the .js include files read from those variables. That’s not a good solution. It would be much better if the .js files could be rendered with the localized text directly.
At work, I’ve written exactly such a mechanism and here is a cleaned up, plug ‘n play version you can use in your own web project. It’s an HttpHandler that intercepts the requests to the .js files and performs the localization based on regular expressions. Here’s how it works.
Resource files
It doesn’t matter whether you use .resx files or satellite assemblies for localizing your text, because both methods work with the System.Resources.ResourceManager class.
A resource file contains keys and a values. The key is always the same, but the value varies for each language. Each language is represented in its own .resx file and the name of the file decides which language it contains like below.
If no language is added in the file name, it automatically becomes the default localizations – normally English. The three .resx files each contain one line with the key nameOfPage. The value in each of the files is localized text that can be referenced by the key.
text.resx: Name of page
text.da.resx: Sidens navn
text.es.resx: Namo de la pago (Sorry, my Spanish is slightly rusty)
The script method
In the .js script files you need a way to specify a certain text as localizable. I’ve chosen to pick a syntax that looks like this:
<script type="text/javascript">
alert(‘Translate(nameOfPage)’);
</script>
Notice that the Translate method above takes the localizable key as parameter. This is the syntax the regular expression in the HttpHandler is looking for.
The HttpHandler
The HttpHandler does a couple of things. It reads the content of the script file, localizes the text, caches the response and compresses it using HTTP compression. It does all this in about 150 lines of easy readable code.
To make it work, you need to update your script references a little bit. Instead of pointing to /scripts/messages.js you need to append .axd to the end of the reference so it becomes /scripts/messages.js.axd. Then you need to add this line to the web.config so that the new script reference actually works.
<httpHandlers>
<add verb="*" path="*.js.axd" type="ScriptTranslator" />
</httpHandlers>
If your site isn’t yet localized you probably need to add the uiCulture attribute to the globalization element in the web.config and set its value to auto.
<globalization uiCulture="auto" />
This will trigger the correct .resx file to be used based on the visiting browser’s language. If your .resx files aren’t called text.resx or you use satellite assemblies, then you need to update the instantiation of the ResourceManager in the TranslateScript method in the handler.
Download code and sample
Download the code below and place the ScriptTranslator.cs in your App_Code folder. Then update your web.config with the web.config values found in the zip file. If you unzip the zip file, the entire contents can be opened directly in Visual Studio and you will be able to try it out easily.
Comments
Very cool solution, I learned to love HttpHandlers thanks to your blog =) It's "Nombre de la página" in spanish by the way
JuanNice and clean solution Mads. COOL! Good work! Thank you for share your knowledge with us
Davide EspertiniLocalize text in JavaScript files in ASP.NET You've been kicked (a good thing) - Trackback from DotNetKicks.com
DotNetKicks.comPingback from blog.cwa.me.uk Reflective Perspective - Chris Alcock » The Morning Brew #164
blog.cwa.me.ukPingback from alvinashcraft.com Dew Drop - August 22, 2008 | Alvin Ashcraft's Morning Dew
alvinashcraft.comThank you, Mads, for sharing an important piece of knowledge.
Mike Borozdinthx, great solution.
asp.netThis is a great solution. However, I ran into a hitch. Supposing I keep all localized javascripts strings in one single location (as in global resource), How can I use resource manager to access global reource within the handler. Thanks.
G SulemanHi all My last question was incomplete. I forgot to add that I am using customresourceprovider. I store values in sql server and access it through a custom resource provider.
G SulemanHi all I have found the solution to my query above. I changed the resourcemenager to my customprovider and created and instance of GlobalResourceProvider from the provider factory. And GetObject just worked normally. Thanks.
G SulemanAmazing web development articles of Summer 2008 Amazing web development articles of Summer 2008
Janko At Warp SpeedPingback from javapronews.com Java Programming News » Blog Archive » Using JavaScript to Localize Text - JavaProNews.com
javapronews.comCool script, but does not work yet in my solution. I receive the error: The type or namespace name 'text' does not exist in the namespace 'Resources' (are you missing an assembly reference?)
BoahEdit for upper message. I made a mistake. Sorry! I changed the name of the resource file to something else. Now it works for me too.
BoahAmazing web development articles of Summer 2008 The summer is near its end and I think it's a good time to see what was hot during past three months
Morning BreakHi Mads, i ve got some addition to your code.If one uses a dropdownlist to select a culture=language your code can not sense it so i changed it a bit: it implements IRequiresSessionState now. i got culture from session at initializeculture. (that is public class ScriptTranslator : IHttpHandler, IRequiresSessionState) and i use resourceset for dropdown case. public void ProcessRequest(HttpContext context) { string relativePath = context.Request.AppRelativeCurrentExecutionFilePath.Replace(".axd", string.Empty); string absolutePath = context.Server.MapPath(relativePath); string script = ReadFile(absolutePath); string translated; if (context.Session != null && context.Session["MyUICulture"] != null) { CultureInfo currentCultureInfo = (CultureInfo)context.Session["MyUICulture"]; translated = TranslateScript(script, currentCultureInfo); } else { translated = TranslateScript(script); } context.Response.Write(translated); Compress(context); SetHeadersAndCache(absolutePath, context); } #endregion /// <summary> /// This will make the browser and server keep the output /// in its cache and thereby improve performance. /// </summary> private void SetHeadersAndCache(string file, HttpContext context) { context.Response.AddFileDependency(file); } #region Localization private static Regex REGEX = new Regex(@"Translate\(([^\))]*)\)", RegexOptions.Singleline | RegexOptions.Compiled); /// <summary> /// Translates the text keys in the script file. The format is Translate(key). /// </summary> /// <param name="text">The text in the script file.</param> /// <returns>A localized version of the script</returns> private string TranslateScript(string Site, CultureInfo currentCultureInfo) { MatchCollection matches = REGEX.Matches(Site); ResourceManager manager = new ResourceManager(typeof(Resources.Site)); ResourceSet resourceSet = manager.GetResourceSet(currentCultureInfo, true, true); foreach (Match match in matches) { object obj = resourceSet.GetObject(match.Groups[1].Value); if (obj != null) { Site = Site.Replace(match.Value, CleanText(obj.ToString())); } } return Site; }
melih gümüşçaythanks for this post, it's really helpful :)
BelajarExcellent solution. Just what I was looking for.
AlPingback from dnasir.com Localising your JavaScript in ASP.NET ← Dzulqarnain Nasir
dnasir.comComments are closed