Using JQuery.i18n.properties for internationalization of web front end

Source: Internet
Author: User
Tags i18n response code vars

Internationalization is now an important part of WEB application development. JQuery.i18n.properties is a lightweight jQuery internationalization plugin that enables the internationalization of the Web front end without making any changes to the backend. The JQuery.i18n.properties plug-in is simple, easy to use, and loosely coupled compared to other international tools. Through practical examples, this paper introduces how to realize the internationalization of Web front end through jQuery.i18n.properties plug-in. Code download

JQuery.i18n.properties Introduction

Before introducing JQuery.i18n.properties, let's take a look at what internationalization is. The internationalized English word is: internationalization, also called i18n, "I" is the first letter of the word, "18" is the number of words between "I" and "N", and "N" represents the last letter of the word. In the computer field, internationalization refers to the process of designing software that adapts to various regional and linguistic environments.

The jQuery.i18n.properties is a lightweight jquery internationalization plugin. Similar to the resource files in Java, JQuery.i18n.properties uses the. properties file to internationalize JavaScript. The JQuery.i18n.properties plugin resolves a resource file with a ". Properties" suffix based on the user-specified (or browser-provided) language and country code (conforming to the ISO-639 and ISO-3166 standards).

Using resource files for internationalization is a popular way, such as Android apps that can be internationalized with resource files named for language and country code. The resource file in the JQuery.i18n.properties plugin is suffixed with ". Properties", which contains the zone-related key-value pairs. We know that Java programs can also be internationalized using resource files with the. Properties suffix, so this is especially useful when we want to share resource files in Java programs and front-end JavaScript programs. The JQuery.i18n.properties plugin first loads the default resource file (for example: strings.properties) and then loads the resource file for the specific locale (for example: Strings_ Zh.properties), which guarantees that the default value is always valid when translations for a language are not available. A developer can use a key from a resource file in a JavaScript variable (or function) or MAP.

Overall, JQuery.i18n.properties has some features:

1. Using the Java standard. properties file as a resource file, the resource file is named in the following three formats:

2. Basename_properties

3. Basename_language.properties

Basename_language_country.properties

    1. Using ISO-639 as the language encoding standard, ISO-3166 as the country name coding standard
    2. Load default resource files sequentially and resource files for the specified locale, ensuring that the default values are always available
    3. Use the language provided by the browser when no locale is specified
    4. You can use placeholders in the resource string (for example: hello= Hello {0}! Today is {1}. )
    5. The Key in the resource file supports namespaces (for example: Com.company.msgs.hello = hello!)
    6. Support for values across rows
    7. You can use a Key from a resource file in a JavaScript variable (or function) or MAP.

JQuery.i18n.properties API

The JQuery.i18n.properties API is very simple, with only a few APIs, namely JQuery.i18n.properties (), JQuery.i18n.prop (), JQuery.i18n.browserLang ( )。 Of course, as with other jQuery plugins, we can use these APIs in the form of $.i18n.properties (), $.i18n.prop (), and $.i18n.browserlang ().

JQuery.i18n.properties (Settings)

This method loads the resource file, where settings is a series of key-value pairs that configure the load option, as shown in table 1 for the specific description of each configuration item.

Table 1. Settings

Options

Describe

Type

Optional?

Name

The name of the resource file, such as strings or [STRINGS1,STRINGS2], which represents a resource file, which represents an array of resource files.

String or string[]

Whether

Path

The path to the directory where the resource file resides

String

Is

Mode

Load mode: "VARs" means using the key in the resource file as a JavaScript variable or function, "map" means using the key in the resource file as a map, and "both" means that it can be used in both ways. If the key in the resource file contains JavaScript keywords, you can only use "map". The default value is "VARs".

String

Is

Language

ISO-639 The specified language encoding (e.g. "en" for English, "zh" for Chinese), or both the language encoding specified by ISO-639 and the ISO-3166 of the specified country code (e.g. "en_US", "ZH_CN", etc.). If not specified, the language encoding that is reported by the browser is used.

String

Is

Cache

Specifies whether the browser caches resource files and defaults to False.

Boolean

Is

Encoding

The encoding to use when loading the resource file. The default is UTF-8.

String

Is

Callback

callback function to run when code execution is complete

function

Is

The use of JQuery.i18n.properties () is shown in Listing 1.

Listing 1. JQuery.i18n.properties () Usage

JQuery.i18n.properties ({

Name: ' Strings ',//resource file name

Path: ' bundle/',//directory path where the resource file resides

Mode: ' Both ',//pattern: variable or MAP

Language: ' pt_pt ',//the corresponding language

Cache:false,

Encoding: ' UTF-8 ',

Callback:function () {//callback method

}

});

JQuery.i18n.prop (Key)

The method uses the value in the resource file as a map, where key refers to the key in the resource file. When the value specified by key contains a placeholder, you can use the form JQuery.i18n.prop (Key,var1,var2 ...), where var1,var2 ... Replace each placeholder in turn. For example, the resource file has "msg_hello= Hello {0}, today is {1}." "The key value pair, then we can adopt" JQuery.i18n.prop (' Msg_hello ', ' xiaoming ', ' Monday '); " In the form of using Msg_hello.

JQuery.i18n.browserLang () is used to obtain language information for browsing the browser, which is no longer described separately.

Example

Here's a concrete example of how to internationalize the Web front end with the JQuery.i18n.properties plugin. We set up a Java Web app called hello-i18n, which displays the login interface in English or Chinese based on the language of the browser, displays the welcome message in the appropriate language after the login is successful, and displays the error message in the appropriate language if the login fails.

To achieve loose coupling, the front end is implemented with pure javascript+html (our goal is to introduce how to internationalize, not how to beautify the interface, so we do not use CSS), and the server side uses RESTFul Web services. The front end interacts with the server side through JQuery Ajax, avoiding the phenomenon of the back-and-forth code jumbled together in traditional Java Web applications such as JSP.

Developing a test environment

    • Operating system: Windows7 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 Services

We use Apache Wink for server-side RESTful Web services (for the use of Apache Wink for restful Web services, refer to the reference for Wink in the "Resources" section), which implements the user authentication function Yes. Since our focus is not on the server side, we do not actually validate the user, but rather simulate the authentication function and generate a fake key (in the real world, the key will be used to authenticate other rest requests). The REST API is shown in table 2, and the code is shown in Listing 2.

Table 2. REST API

Property

Describe

Describe

Validating user information and generating 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-Validation Successful
401:unauthorized-Incorrect password
403:forbidden-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) {

Impersonation verification function, validation succeeds only if 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 an impersonation 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 Strings.properties and stirngs_zh.properties two resource files in the i18n directory, where strings.properties corresponds to the default translation, as shown in Listing 3; string_ The zh.properties 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 use JQuery.i18n.properties, your key is: {1}.

string_usernotexist= user does not exist

string_wrongpassword= Password Error

Referencing the JQuery.i18n.properties plugin

Like other jquery plugins, the JQuery.i18n.properties plugin relies on jquery, so we first need to refer to jquery. JQuery.i18n.properties has no explicit requirements for the JQuery version, here we use jQuery-1.7.1. We refer to the JQuery and JQuery.i18n.properties plugins in index.html in the way shown in Listing 5.

Listing 5. Reference 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>

The interface elements are also defined in index. HTML, 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>

Using the JQuery.i18n.properties plugin

In Main.js, the resource file is loaded using the method shown in Listing 7, and the "language" parameter option is not specified in Listing 7, which indicates the use of the browser language. In addition to using the values defined in the resource file in the callback function defined by JQuery.i18n.properties (), we can also use these values elsewhere, after the resource file has been successfully loaded.

Listing 7. Load resource File

Functionloadproperties () {

JQuery.i18n.properties ({//load resource file for browser language

Name: ' Strings ',//resource file name

Path: ' resources/i18n/',//resource file path

Mode: ' Map ',//use the values in the resource file in map mode

Callback:function () {////After loading successfully set display content

Show "User Name"

$ (' #label_username '). HTML ($.i18n.prop (' string_username '));

Show "Password"

$ (' #label_password '). HTML ($.i18n.prop (' String_password '));

Show "Login"

$ (' #button_login '). Val ($.i18n.prop (' String_login '));

}

});

}

When the user clicks the login button, we use the REST request to send the user information to the RESTFul WEB service defined earlier, and if the user information is validated successfully, the welcome message and the key returned by the Web service are displayed, and if the validation 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 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) {

Verify success Displays welcome message and key

Use a value with placeholders

$ (' #content '). HTML ($.i18n.prop (' String_hello ', Id,data.token));

},

Error:function (JQXHR, Textstatus, Errorthrown) {

if (Jqxhr.status ==403) {

User does not exist

Alert ($.i18n.prop (' string_usernotexist '));

}elseif (Jqxhr.status = = 401) {

Password error

Alert ($.i18n.prop (' String_wrongpassword '));

}else{

Additional exception information

alert (Errorthrown);

}

}

});

});

Run effect

Deploy the HELLO-I18N project to a local Tomcat, open the Chrome browser, set the language to English, and enter http://localhost:8080/hello-i18n in the Address bar.

Problems and improvements

Resource file naming issues

In the above example, our program only automatically recognizes both Chinese and English translations, and cannot further differentiate between Simplified Chinese and traditional Chinese. To enable the above example to automatically differentiate between Simplified Chinese and traditional Chinese according to the browser language setting, we renamed the resource file Strings_zh.properties to Strings_zh_cn.properties, and added the following as listing 9 The traditional Chinese resource file shown in Strings_zh_tw.properties.

Listing 9. Strings_zh_tw.properties

String_username= User Name

string_password= Password

string_login= Log In

string_hello= Hello {0}, Welcome to use JQuery.i18n.properties, your secret keys is: {1}.

string_usernotexist= user does not exist

string_wrongpassword= Password Bug

Run the program, the browser language is set to "Chinese (Simplified Chinese)" and "Chinese (Traditional Chinese)" to test, found that the program does not appear as we expected to display Simplified Chinese and Traditional Chinese, but both in English display. After analysis, it is found that the cause of this phenomenon is that the default resource file naming method of the JQuery.i18n.properties plugin is inconsistent with the language area code escalated by the browser, which causes the plugin to fail to load the resource file. In Simplified Chinese, for example, the jQuery.i18n.properties default resource file naming method is "ZH_CN", while the browser escalation language area code is ZH-CN "form, at this time jQuery.i18n.properties The steps for the plugin to load the resource file are as follows:

    1. Load the default resource file, which is Strings.properties, succeeds.
    2. Failed to load a resource file named Strings_zh.properties.
    3. Failed to load a resource file named Stirngs_zh-cn.properties.

Since both steps 2nd and 3rd fail, JQuery.i18n.properties uses the translation in the default resource file Strings.properties, which is the English translation. Similarly, traditional Chinese is not displayed properly. There are 3 ways to solve this problem:

    1. Name the resource file in strings_zh-cn.properties manner. This is the simplest method, but this naming method and Java standard resource file naming method is inconsistent;
    2. Use the default resource file naming method and explicitly get the language of the browser using var lang = JQuery.i18n.browserLang () before calling the JQuery.i18n.properties () method, and then replace "-" in Lang with "_" and use Lang as the parameter when using the JQuery.i18n.properties () method.
    3. Change the source code of JQuery.i18n.properties.

Here we use the simplest first way, the simplified Chinese corresponding resource file string_zh_cn.properties renamed to Stirngs_zh-cn.properties, and the traditional Chinese counterpart of the resource file Strings_zh_ Tw.properties renamed to Strings_zh-tw.properties. Now the program can automatically differentiate between Simplified Chinese and traditional Chinese based on browser language settings .

Summarize

This paper introduces the JQuery internationalization plugin jQuery.i18n.properties, and introduces how to use JQuery.i18n.properties plug-in to realize the internationalization of Web front-end. Summing up, JQuery.i18n.properties has a lightweight (4KB only after compression), easy to use and so on, but as a low-prevalence lightweight plug-in, not necessarily suitable for large-scale or high efficiency requirements of the scene.

I hope this article can provide some reference for the readers who are looking for the international solution of small WEB application front end.

Using JQuery.i18n.properties for internationalization of web front end

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.