javascriptasp.netglobalization

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?


Solution

  • 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>