Mhm
Mhm

Reputation: 45

How to utilize globalization in JavaScript?

I have created 3 resx files in App_GlobalResources folder in asp.net project in order to make a multilingual website, as you know it's sort of key-value set, everything seems good else cases in which I want to use values in JavaScript.

If I use inline JavaScript in aspx file it can be done using this way or

alert('<%= GetGlobalResourceObject([ResourceClassName],[ResourceKey]) %>');

Or

<asp:Literal runat="server" Text="<%$ Resources:[ResourceClassName], [ResourceKey] %>"/>

but how should I achieve that in JavaScript files in which I am not able to use server side code?

Upvotes: 1

Views: 1684

Answers (2)

mitsugui
mitsugui

Reputation: 11

To find information on globalization support in ASP.NET, see this Microsoft page. According to the page, ScriptManager can deliver different scripts based on the user's culture.

Upvotes: 1

Muhammad Musavi
Muhammad Musavi

Reputation: 2696

I use a structure similar to what we use in ASP.Net and I apply JavaScript object like what CKEditor uses in multilingual feature.

Imagine you have these files:

Culture.js
Main.js
Default.aspx

Culture.js

Place all words and phrases related to translations like this:

  if (typeof resource == "undefined") {
    resource = {}// = new Object();
    resource.lang = {};
  }

    //English language, United States culture
    resource.lang['en-US'] = {
        "lable": {
            "clickHere": "Click here",
            "enterYourName": "Enter your name"
        },
        "message": {
            "deleteConfimation": "Are You sure you want to delete?",
            "accessIsDenied": "Access is denied"
        }
    }

    //Farsi language, Iran culture 
    resource.lang['fa-IR'] = {
        "lable": {
            "clickHere": "اینجا کلیک کنید",
            "enterYourName": "نام خود را وارد کنید"
        },
        "message": {
            "deleteConfimation": "آیا از حذف این مورد اطمینان دارید؟",
            "accessIsDenied": "دسترسی مقدور نیست"
        }
    }

You can add as much as languages and cultures you need, just use language-culture combination in resourse.lang['language-culture'] to make them distinguishable, finally define a function just like what you use in ASP.Net named getGlobalResourceObject()

 var getGlobalResourceObject = function (resourceClassName, resourceKey)
{
    return resourse.lang[window.lang][resourceClassName][resourceKey];
}

Main.js

window.lang = "en-US";//Or "fa-IR"
alert(getGlobalResourceObject("message", "deleteConfimation"));

It will alert a message saying "Are You sure you want to delete?" if window.lang equals to en-US. (I prefer to set current culture in window.lang).

Default.aspx

In Default.aspx or MasterPage if you have any, load Culture.js just before Main.js, something like this:

<script src="Culture.js"></script>
<script src="Main.js"></script>

Upvotes: 1

Related Questions