Use jQuery. i18n. properties to internationalize the Web Front-end, jqueryi18n
Internationalization is now an important part of Web application development. JQuery. i18n. properties is a lightweight jQuery internationalized plug-in that can internationalize the Web Front-end without making any changes to the backend. Compared with other international tools, the jQuery. i18n. properties plug-in is simple, easy to use, and loosely coupled. This article describes how to use the jQuery. i18n. properties plug-in to internationalize the Web Front-end. Code download
Introduction to jQuery. i18n. properties
Before introducing jQuery. i18n. properties, let's take a look at what globalization is. International English words: Internationalization, also known as i18n. "I" is the first letter of the word, and "18" is the number of words between "I" and "n, "n" represents the last letter of the word. In the computer field, internationalization refers to the process of designing software that can adapt to various regions and Language Environments.
JQuery. i18n. properties is a lightweight jQuery International plug-in. Similar to the resource files in Java, jQuery. i18n. properties adopts the. properties file to internationalize JavaScript. JQuery. i18n. the properties plug-in resolves the corresponding ". properties is a resource file with a suffix.
Using resource files to internationalize is a popular method. For example, Android applications can use resource files named after languages and country codes to internationalize them. The resource file in the jQuery. i18n. properties plug-in is suffixed with ". properties" and contains region-related key-value pairs. We know that Java programs can also use. properties is a suffix of resource files to achieve internationalization. Therefore, this method is particularly useful when we want to share resource files in Java programs and front-end JavaScript programs. JQuery. i18n. the properties plug-in first loads the default resource file (for example, strings. properties), and then load the resource files (for example, strings_zh.properties) for a specific language environment. This ensures that the default value is always valid when translation in a language is not provided. Developers can use keys in resource files using JavaScript variables (or functions) or Map.
In general, jQuery. i18n. properties has the following features:
1. Use the Java standard. properties file as the resource file. The resource file name has the following three formats:
2. basename_properties
3. basename_language.properties
Basename_language_country.properties
- Use ISO-639 as language encoding standard and ISO-3166 as country name encoding standard
- Load default resource files and resource files in the specified language environment in sequence to ensure that the default value is always available
- Use the language provided by the browser when no language environment is specified
- Placeholders can be used in resource strings (for example, hello = hello {0 }! Today is {1 }.)
- The Key in the resource file supports namespaces (for example, com. company. msgs. hello = Hello !)
- Supports cross-row values.
- The Key in the resource file can be used as a JavaScript variable (or function) or Map.
JQuery. i18n. properties API
JQuery. i18n. properties APIs are very simple. There are only a few APIs, namely jQuery. i18n. properties (), jQuery. i18n. prop (), and jQuery. i18n. browserLang (). Of course, like other jQuery plug-ins, we can also use $. i18n. properties (), $. i18n. prop () and $. i18n. use these APIs in the form of browserLang.
JQuery. i18n. properties (settings)
This method loads the resource file. settings is a series of key-value pairs for configuring the loading options. The specific descriptions of each configuration item are shown in table 1.
Table 1. settings
Option |
Description |
Type |
Optional? |
Name |
Resource file name, such as strings or [strings1, strings2]. The former represents a resource file, and the latter represents a resource file array. |
String or String [] |
No |
Path |
Path of the directory where the resource file is located |
String |
Yes |
Mode |
Loading Mode: "vars" indicates that the Key in the resource file is used as a JavaScript variable or function, and "map" indicates that the Key in the resource file is used as a Map, "both" indicates that two methods can be used at the same time. If the Key in the resource file contains the JavaScript keyword, you can only use "map ". The default value is "vars ". |
String |
Yes |
Language |
The language code specified by the ISO-639 (for example, "en" represents English, "zh" represents Chinese), or the country code specified by the language code specified by the ISO-639 and the Country Code specified by the ISO-3166 (such: "en_US", "zh_CN", etc ). If this parameter is not specified, the language of the browser report is used. |
String |
Yes |
Cache |
Specifies whether the browser caches resource files. The default value is false. |
Boolean |
Yes |
Encoding |
The encoding used to load the resource file. The default is UTF-8. |
String |
Yes |
Callback |
The callback function that runs when the code is executed. |
Function |
Yes |
The usage of jQuery. i18n. properties () is shown in Listing 1.
Listing 1. jQuery. i18n. properties () Usage
JQuery. i18n. properties ({
Name: 'string', // resource file name
Path: 'bundle/', // path of the directory where the resource file is located
Mode: 'both ', // mode: variable or Map
Language: 'pt _ pt ', // corresponding language
Cache: false,
Encoding: 'utf-8 ',
Callback: function () {// callback Method
}
});
JQuery. i18n. prop (key)
This method uses the value in the resource file as map, where key refers to the key in the resource file. When the value specified by the key contains placeholders, you can use jQuery. i18n. prop (key, var1, var2... ), Where var1, var2... Replace placeholders in sequence. For example, the resource file contains "msg_hello = Hello {0}. Today is {1 }." In the form of "jQuery. i18n. prop ('msg_hello ', 'xiaoming', 'monday.
JQuery. i18n. browserLang () is used to obtain the language information of the browser.
Example
The following example shows how to use the jQuery. i18n. properties plug-in to internationalize the Web Front-end. We create a Java Web application named hello-i18n, the application according to the browser language decided to display the login interface in English or Chinese, login successful after the corresponding language display welcome information, if logon fails, an error message is displayed in the corresponding language.
To achieve the goal of loose coupling, the front end is implemented using pure JavaScript + HTML (our purpose is to introduce how to internationalize, rather than how to beautify the interface, so CSS is not used for the moment ), the server uses RESTFul Web Services. The front-end interacts with the server through jQuery Ajax to avoid redundant front-end code in JSP and other traditional Java Web applications.
Development and testing environment
- Operating System: Windows 7 64-bit Professional Edition.
- IDE: Eclipse-JEE-Juno.
- Libs: jQuery 1.7.1, jQuery. i18n. properties 1.0.9, Apache Wink 1.1.3.
- Test Browser: Google Chrome 21.0.1180.83 m, FireFox 15.0.1.
Server-side RESTFul Web Service
We use Apache Wink to implement server-side RESTFul Web services (for details about how to use Apache Wink to implement RESTFul Web Services, refer to Wink reference in "references ), this Web Service implements user authentication. Because our focus is not on the server side, we do not really verify the user, but instead simulate the verification function and generate a false key (in a real environment, the key is used to verify other REST requests ). The rest api is shown in table 2 and the code is shown in Listing 2.
Table 2. REST API
Attribute |
Description |
Description |
Verify user information and generate a key |
URI example |
Http: // localhost: 8080/rest/users/{id}/tokens |
HTTP request type |
POST |
Request Boy |
{Password :"..."} |
Response Headers |
Content-type: application/json |
Response Code |
200: OK-Verification Successful 401: Unauthorized-Incorrect password 403: Forbidden-the user does not exist |
Response Body |
{Token: "Y29udHJvbGxlci5yZWFkIiwib3BlbmlkIiwicGFzc dvcQd3Jp dGUiXSwiZW ..."} |
Listing 2. REST code
@ Path ("/users ")
Public classRESTApi {
@ Path ("/{id}/tokens ")
@ POST
@ Produces ({MediaType. APPLICATION_JSON })
@ Consumes ({MediaType. APPLICATION_JSON })
Public Responseauthenticate (@ PathParam ("id") String id,
Map <String, Object> payload ){
// Simulate the verification function. The verification is successful only when the user name is "i18n" and the password is "123456 ".
If (id. equals ("i18n ")){
String pwd = (String) payload. get ("password ");
If (pwd. equals ("123456 ")){
// Generate a simulated key
Map <String, String> token = new HashMap <String, String> ();
Token. put ("token ",
"Y29udHJvbGxlci5yZWFkIiwib3BlbmlkIiwicGFzc3dvcmQud3JpdGUiXSwiZW ...");
ReturnResponse. status (Status. OK). entity (token). build ();
} Else {
ReturnResponse. status (Status. UNAUTHORIZED). build ();
}
}
ReturnResponse. status (Status. FORBIDDEN). build ();
}
}
Create a resource file
Create the strings. properties and stirngs_zh.properties resource files under the i18n directory. The strings. properties file corresponds to the default translation, as shown in listing 3. The string_zh.properties file corresponds to the Chinese translation, as shown in Listing 4.
Listing 3. stirngs. properties
String_username = Username
String_password = Password
String_login = Login
String_hello = Hello {0}, Welcome to jQuery. i18n. properties, your token is {1 }.
String_usernotexist = User does not exist
String_wrongpassword = Wrong Password
Listing 4. strings_zh.properties
String_username = User Name
String_password = Password
String_login = Login
String_hello = Hello {0}. Welcome to jQuery. i18n. properties. Your key is {1 }.
String_usernotexist = the user does not exist
String_wrongpassword = incorrect password
Reference jQuery. i18n. properties plug-in
Like other jQuery plug-ins, The jQuery. i18n. properties plug-in depends on jQuery. Therefore, we need to reference jQuery first. JQuery. i18n. properties has no explicit requirements for jQuery versions. Here we use jQuery-1.7.1. We reference jQuery and jQuery. i18n. properties plug-ins in index.html using the method shown in listing 5.
Listing 5. Referencing jQuery. i18n. properties
<Scripttype = "text/javascript" src = "resources/lib/jquery-1.7.1.min.js">
</Script>
<Scripttype = "text/javascript" src = "resources/lib/jquery. i18n. properties-1.0.9.js">
</Script>
Index. html also defines interface elements, as shown in Listing 6.
Listing 6. interface elements
<Divid = "content">
<Div>
<Labelid = "label_username"> </label>
<Inputtype = "text" id = "username"> </input>
</Div>
<Div>
<Labelid = "label_password"> </label>
<Inputtype = "password" id = "password"> </input>
</Div>
<Inputtype = "button" id = "button_login"/>
</Div>
Use the jQuery. i18n. properties plug-in
In main. js, use the method shown in listing 7 to load the resource file. In listing 7, the "language" parameter option is not specified, indicating that the browser language is used. In addition to using the defined values in the resource file in the callback function defined by jQuery. i18n. properties (), we can also use these values elsewhere after the resource file is loaded successfully.
Listing 7. Loading resource files
FunctionloadProperties (){
JQuery. i18n. properties ({// load the resource file corresponding to the asset browser Language
Name: 'string', // resource file name
Path: 'resources/i18n/', // resource file path
Mode: 'map', // use the value in the resource file in map mode
Callback: function () {// set the display content after loading successfully
// Display "User Name"
Condition ('your label_username'your .html ($. i18n. prop ('string _ username '));
// Display the "password"
Certificate ('your label_password'your .html ($. i18n. prop ('string _ password '));
// Display "Logon"
$ ('# Button_login'). val ($. i18n. prop ('string _ login '));
}
});
}
After a user clicks the login button, we use the REST request to send the user information to the previously defined RESTFul Web service. If the user information is verified successfully, the welcome information and the key returned by the Web service are displayed, if verification fails, an error message is displayed, as shown in listing 8.
Listing 8. Front-end login Logic
$ ('# Button_login'). click (function () {// click the login button to verify the user information
Var id = $ ('# username'). val (); // User Name
Var payload = {};
Payload ['Password'] = $ ('# password'). val ();
Payload = $. toJSON (payload );
$. Ajax ({
Url: 'rest/users/'+ id +'/tokens', // rest URI
Type: 'post ',
Data: payload, // Request body
ContentType: 'application/json ',
DataType: 'json ',
Success: function (data ){
// If the verification succeeds, the welcome information and key are displayed.
// Use a value with a placeholder
Parameters ('{content'{.html ($. i18n. prop ('string _ hello', id, data. token ));
},
Error: function (jqXHR, textStatus, errorThrown ){
If (jqXHR. status = 403 ){
// The user does not exist.
Alert ($. i18n. prop ('string _ usernotexist '));
} Elseif (jqXHR. status = 401 ){
// Incorrect password
Alert ($. i18n. prop ('string _ wrongpassword '));
} Else {
// Other exception information
Alert (errorThrown );
}
}
});
});
Running Effect
Deploy the hello-i18n project to a local Tomcat, open the Chrome browser, set language to English, enter http: // localhost: 8080/hello-i18n in the address bar.
Problems and Improvements
Resource file naming
In the above example, our program only automatically recognizes Chinese and English translations, but cannot further distinguish between Simplified Chinese and Traditional Chinese. To enable the preceding example to automatically differentiate between Simplified Chinese and Traditional Chinese Based on browser language settings, rename the resource file strings_zh.properties corresponding to simplified Chinese to strings_zh_CN.properties, add the traditional Chinese resource file strings_zh_TW.properties shown in listing 9.
Listing 9. strings_zh_TW.properties
String_username = use the alias name
String_password = Password
String_login = Login
String_hello = Hello {0}. Welcome to use jQuery. i18n. properties. Your secret is: {1 }.
String_usernotexist = the consumer does not exist
String_wrongpassword = password-sensitive Authentication
Run the program and set the browser language to "Chinese (Simplified Chinese)" and "Chinese (Traditional Chinese)" for testing, we found that the program could not display both Simplified Chinese and Traditional Chinese as we expected, but both in English. After analysis, it is found that the cause of this phenomenon is jQuery. i18n. the default resource file naming method of the properties plug-in is inconsistent with the language and region encoding reported by the browser, causing the plug-in to fail to load the resource file. Take Simplified Chinese as an example, jQuery. i18n. the default resource file naming method of properties is "zh_CN", and the language area reported by the browser is encoded as zh-CN. In this case, jQuery. i18n. the steps for the properties plug-in to load the resource file are as follows:
- The default resource file strings. properties is loaded successfully.
- Failed to load the resource file named strings_zh.properties.
- Failed to load the resource file named stirngs_zh-CN.properties.
Because both steps 2nd and 3rd fail, jQuery. i18n. properties uses the translation in the default resource file strings. properties, that is, the English translation. Similarly, traditional Chinese cannot be displayed normally. There are three solutions to this problem:
- Name the resource file as a strings_zh-CN.properties. This is the simplest method, but this naming method is inconsistent with the standard resource file naming method in Java;
- Use the default resource file naming method and call jQuery. i18n. before the properties () method, use var lang = jQuery. i18n. browserLang () is used to explicitly obtain the browser language, replace "-" with "_" in lang, and use jQuery. i18n. lang is used as a parameter in the properties () method.
- Change the source code of jQuery. i18n. properties.
Here we use the simplest first method, rename the resource file string_zh_CN.properties corresponding to simplified Chinese to the stirngs_zh-CN.properties, and rename the resource file strings_zh_TW.properties corresponding to traditional Chinese to the strings_zh-TW.properties. Now, the program can automatically distinguish between Simplified Chinese and Traditional Chinese Based on the browser language settings..
Summary
This article introduces jQuery. i18n. properties, the jQuery International plug-in, and introduces how to use the jQuery. i18n. properties plug-in to internationalize the Web Front-end. To sum up, jQuery. i18n. properties is lightweight (only 4 kb after compression) and easy to use. However, as a lightweight plug-in with low popularity, properties is not necessarily applicable to large or highly efficient scenarios.
I hope this article will provide some reference for readers who are looking for small Web application frontend internationalization solutions.