开发者

Want to create a multilingual javascript object, how to handle if lots of labels?

开发者 https://www.devze.com 2023-01-02 04:56 出处:网络
I want to create a javascript file for multilingual functionality i.e. display the error message in the correct language.

I want to create a javascript file for multilingual functionality

i.e. display the error message in the correct language.

If I have allot of labels for a page, error mess开发者_JAVA百科ages, etc., what is a smart way of making this so the actual output on the page isn't huge?

i guess the best way is to somehow output the labels that I need ONLY?

lang.getkey('username');

will output the correct label, depending on the language.


Language detection is usually done server-side by checking the Accept-Language HTTP header that is sent.

Browsers have limited, non-standardized means for identifying a user's language (with the exception of IE running on Windows). With IE on Windows, you can access navigator.userLanguage or navigator.systemLanguage, which will return the operating system's RFC #4646 language-COUNTRY code. Other browsers (Opera, Safari, Chrome, Firefox) provide navigator.language, which is in the same format with the exception of Opera which returns the language only. In many cases this might be good enough, but it's still recommended to use a server solution.

I achieved something like this a while ago by separating the strings into different lang.js files and added the script to the document using document.write(). The function would simply fetch the string from an array defined in that lang.js file. A basic example might be:

// Get the language-COUNTRY code, and strip it to the language part only
var lang = (navigator.language || navigator.userLanguage).substring(0,2);
var file = "lang/" + lang + ".js";

document.write('<script src="'+lang+'" type="text/javascript"><\/script>');

This would ensure that only the strings for the necessary language were loaded, although I haven't included a fallback method here, you would need one for defaulting to a language when an unsupported one was detected. You could do this by having a list of supported languages in an array, check to see if lang exists and if it doesn't, write a default script src instead.

Not to sound like a broken record, but you should probably be determining languages and including files server side, not client side.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号