如何在JavaScript中利用全球化? [英] How to utilize globalization in JavaScript?
问题描述
我已经在asp.net
项目的App_GlobalResources
文件夹中创建了3个resx文件,以便建立一个多语言网站,因为您知道它是key-value
集合的一种,在我要使用值的其他情况下,一切似乎都不错在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.
如果我在aspx文件中使用内联JavaScript,则可以使用此方式或
If I use inline JavaScript in aspx file it can be done using this way or
alert('<%= GetGlobalResourceObject([ResourceClassName],[ResourceKey]) %>');
或
<asp:Literal runat="server" Text="<%$ Resources:[ResourceClassName], [ResourceKey] %>"/>
但是如何在无法使用服务器端代码的JavaScript文件中实现该目标?
but how should I achieve that in JavaScript files in which I am not able to use server side code?
推荐答案
我使用类似于ASP.Net
中使用的结构,并且应用JavaScript对象,例如CKEditor
在多语言功能中使用的对象.
I use a structure similar to what we use in ASP.Net
and I apply JavaScript object like what CKEditor
uses in multilingual feature.
假设您有以下文件:
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": "دسترسی مقدور نیست"
}
}
您可以添加所需的多种语言和文化,只需在resourse.lang['language-culture']
中使用language-culture
组合使其可区分,最后定义一个函数,就像在ASP.Net中使用的名为getGlobalResourceObject()
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"));
它将提示您确定要删除吗?"的消息.如果window.lang
等于en-US
.
(我更喜欢在window.lang
中设置当前的区域性.)
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
在Default.aspx
或MasterPage
中,如果有的话,在Main.js
之前加载Culture.js
,如下所示:
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>
这篇关于如何在JavaScript中利用全球化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!