I searched for information and found that most of the js files in different languages are made separately, and then the corresponding js files are loaded according to the user's locale.
But now due to usage scenario limitations, it is best to complete it in a js file. I now plan to support 3 languages (Chinese, Japanese, English), and there are many places to output text, maybe hundreds of lines, and variables are often spliced in the middle.
var result=10;
document.body.innerHTML="一共有"+result+"个结果";
Now I have two ideas. One is to save the language text in a variable; the other is to write the text in place in the form of an array, and then call it using subscripts.
// 方式1:判断语言后确定唯一的结果。有点割裂,而且在使用时只能看到属性名,影响思路
// {w1}是占位符,每个配置写了多遍是为了模拟数量多的时候的情景
var lang={};
if () { // 判断为中文
lang.tip1="一共有{w1}个结果";
// lang.tip2="一共有{w1}个结果";
// lang.tip3="一共有{w1}个结果";
// lang.tip4="一共有{w1}个结果";
// lang.tip5="一共有{w1}个结果";
}else if(){ // 判断为日文
lang.tip1="{w1}の結果の合計";
// lang.tip2="{w1}の結果の合計";
// lang.tip3="{w1}の結果の合計";
// lang.tip4="{w1}の結果の合計";
// lang.tip5="{w1}の結果の合計";
}else if(){ // 判断为英文
lang.tip1="There is a total of {w1} result";
// lang.tip2="There is a total of {w1} result";
// lang.tip3="There is a total of {w1} result";
// lang.tip4="There is a total of {w1} result";
// lang.tip5="There is a total of {w1} result";
}
var result=10;
document.body.innerHTML=lang.tip1.replace("{w1}",result);
// 方式2:判断语言后只做个下标,文字写在原地方。这样使用时可以知道这里写的是什么,但似乎比较乱
var lang;
if () { // 判断为中文
lang=0;
}else if(){ // 判断为日文
lang=1;
}else if(){ // 判断为英文
lang=2;
}
var result=10;
document.body.innerHTML=["一共有{w1}个结果","{w1}の結果の合計","There is a total of {w1} result"][lang].replace("{w1}",result);
In fact, the first method is more elegant in form, but I personally prefer the second method, mainly because I know what is written here when I look at the code. It is more troublesome to judge the content by variable names (mainly because there are too many entries. Although I need to semantically process the variable names for actual use, there are not many cases where the content can be described briefly and accurately).
Do you have any other ideas or solutions?
You probably want to translate all the text, but due to the grammatical structure problem, the location of the variables is unknown and you don’t know how to solve it?
In terms of ideas, you can actually refer to the idea of template rendering.
Let me give you an analogy
Like this?
Your problem is within the scope of i18n/L10n, maybe you can find something like
jQuery.i18n
JavaScript I18n And L10n
Internationalization and localization javascript libraries. The first library was created by Wikimedia and is of great reference value.
Other basic i18n/L10n content and libraries, don’t miss it
Unicode CLDR such as Simplified Chinese language table
ICU library
I am very interested in the development of i18n/L10n in China, and we will learn and grow together.