Thursday, September 4, 2008

Localizing text in Javascript

How do you make text that is rendered via Javascript localizable? Here I'll share how I solved this on a recent project.
Here's some Javascript code embedded in a page:
<button onclick="alert('You got me!');">Click me</button>

Changing the button label to localizable text can be done by turning this button into a server side control:
<asp:button onclick="alert('You got me!');" text="<%Resources: Button_ClickMe %>" runat="server"/>

Where the button label is now defined as a (page local) string resource called Button_ClickMe. We still need to put the "You got me!" text into a string resource and pass that to the Javascript code some how.

Fortunately ASP.Net provides some handy functionality in the ScriptManager class that allows injection of code into the generated page. The ScriptManager.RegisterExpandoAttribtute is particularly useful - it allows any arbitrary attribute on any DOM object to be assigned a value. I decided to make use of this to store localizable strings as attributes on an object in the DOM.
Because I want to be able to use this functionally across multiple pages, I have defined a new base page, GlobPage (derived from System.Web.UI.Page) for all of my localizable pages to inherit from. My GlobPage class adds an empty Div control to the page to act as the placeholder for storing localized strings.
protected override void OnInit(EventArgs e)
LocTextContainer = new HtmlGenericControl("div");
LocTextContainer.ID = "LocalizedTextContainer";
Page.Controls.AddAt(1, LocTextContainer);

GlobPage also defines the following function to add localized string values to the LocalizedTextContainer Div
protected void RegisterJavascriptLocalStringResource(string key)
Page.ClientScript.RegisterExpandoAttribute("LocalizedTextContainer", key, (string)GetLocalResourceObject(key));
In the code behind of my page that holds the "Click Me" button I add the following to the Page_Load() method:

This puts the localized text that is defined on the Button_Response string resource into an attribute called "Button_Response" on the LocalizedTextContainer div in the generated page.
It can then be accessed from Javascript by simply using the expression LocalizedTextContainer.Button_Response as in the following:
<asp:button onclick="alert(LocalizedTextContainer.Button_Response);" text="<%Resources: Button_ClickMe %>" runat="server"/>
So don't be afraid to use Javascript in a globalized web application - it can be done!

1 comment:

Praveen59 said...

In which namespace do we have ScriptManager class? Is it necessary to install AJAX extensions to work with ScriptManager class?