Localize JavaScript files in SharePoint

In a project I was working on, I needed a way to localize strings in JavaScript files in order to support different languages in the application. The solution was designed to be a SharePoint sandboxed solution, so we could not deploy custom resx files to the file system (this article by Waldek Mastykarz explains how to use ScriptResx.ashx to be able to refer to resource strings inside JavaScript files).

In order to solve the problem, we added one JavaScript file for each language and named it res.cc-ll.js

(for example res.en-us.js and res.sv-se.js), and added code to our custom master page to register the correct JavaScript file based on the current language. We used the $SPUrl command in SharePoint, and the two tokens ~SiteCollection and ~language to find the relative url of the site collection and the current language, respectively.

<script type="text/javascript" language="javascript" src='<asp:Literal runat="server" Text="<%$SPUrl:~SiteCollection/Style Library/Custom/scripts/res.~language.js%>" />'></script>

The rendered code for the above could for example will be:

<script type="text/javascript" language="javascript" src='/Style Library/Custom/scripts/res.en-US.js'></script>

The content of these localized JavaScript files is shown below using “en-us” as an example. It contains a JavaScript array of text constants that is translated for the chosen language. We could have made this array publicly available, but decided to create a method that returns a default value if the key we are looking for does not exist.

window.AppRes = window.AppRes || {};

window.AppRes.Constants = (function () {
    'use strict';

    // Declare the text constant array
    var textConstants = {
        Step1: "Registration",
        Step2: "Risk assesment",
        Step3: "Corrective actions",
        Step4: "Complete issue",
        Step5: "Workflow completed"
    }

    var getTextConstant = function (key, defaultValue) {
        if (typeof key === 'undefined' || key === '' || typeof textConstants[key] === 'undefined')
            return defaultValue;
        return textConstants[key];
    }

    return {
        // Get the text constant from a key, provide default value if key does not exist
        GetTextConstant: function (key, defaultValue) {
            return getTextConstant(key, defaultValue)
        }
    }

})();

Then, from our main custom application scripts, we use the following syntax to find the localized text constant for a given key:

var step1Constant = window.AppRes.Constants.GetTextConstant("Step1", "Registration");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s