简体   繁体   中英

What is the recommended way to enable multiple language support for Javascript displayed text

A number of times I have needed to support multiple languages when building web sites but have yet to come up with a good way of passing the language strings from the server to the client so that they can be used in Javascript for dialogs, messages, etc.

What are your recommendations or experience with this?

EDIT: I'm leaning towards generating the javascript language files on the fly and would appreciate it if anyone knows any third party libraries that can do this.

I usually move all string specification to separate files and then include the appropriate one on the page, something like this:

In st/js/messages-ru.js:

hello = "Привет"
bye = "Пока"

In st/js/messages-en.js:

hello = "Hello!"
bye = "Good bye!"

When the page is generated, you can determine the language and insert the appropriate js file on the page.

Generate the language dependent portion of javascript on the fly handling locale. For performance cache the language specific javascript, once it is generated for a given locale. This saves from maintaining too many language specific javascripts

We pass an object to the JavaScript method that requires translations, and populate that object from server side code:

<script type="text/javascript">
    var dialogl10n = {
        caption: '<%= Resources.GetString(x => x.DialogCaption) %>',
        okButton: '<%= SharedResources.GetTerm(x => x.Ok) %>'
        cancelButton: '<%= SharedResources.GetTerm(x => x.Cancel) %>'
    };
</script>

In the javascript function:

Foo.Bar.doSomething = function(l10n) {
    alert(l1n0.caption);
}

We're looking at enhancing this to automatically create the JSON object:

onClick='Foo.Bar.doSomething(<%= Resources.GetPackageAsJson(); %>);'

Which would create the equivalent object created by hand above.

没有很好的方法来完成这个问题。但是我或我们的团队有一个沉重的方法,在js中为不同的语言编写不同的字符串,例如,在英国,我们写了一个名为uk.js的js,在fr中我们写了一个fr.js for对话框或消息中的静态表达式。

If you're using the ASP.NET AJAX framework, the ScriptManager control contains various mechanisms for automatically generating javascript from localized .resx files, and sending the correct language to the user based on the standard CultureInfo settings that the rest of the website is using. See this MSDN article for a tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM