Front End Series--jquery front-end internationalization solution "pits Diary"

Source: Internet
Author: User
Tags i18n locale

Recently, the new platform has not been completed, the original old project has put forward a new demand: system internationalization. If the front and back end of a completely separate development model, to do internationalization, is really too simple, there is a ready-made solution, based on node construction of any of the current popular technology selection has a mature program, such as:

    • vue+vue-i18n

    • angular+angular-translate

    • react+react-intl

But now the situation is that the old project does not use this kind of architecture. Speaking of internationalization, bloggers have done a few years ago, in the MVC to achieve internationalization has a common solution, mainly through the way of resource files to define multiple languages. Initially received this task, and there is not much concern, after all, this kind of thing has a very mature solution, the difficulty of implementation is not very big. But when the real moving hands come to realize the time to find some problems, here first introduce our old platform architecture: MVC+WEBAPI,MVC Project responsible for page rendering, WEBAPI responsible for data interface, is a very traditional architecture. Internationalization is mainly in the MVC side to do, but because the MVC project uses a lot of third-party bootstrap components, almost 95% of the components are through JS to achieve, such as bootstraptable, such as Bootstrap-select, Like Bootstrap-fileinput. If in the traditional way, only in the MVC to achieve internationalization, then a large number of JS code inside the Chinese can not be unified processing, and many third-party components have their own localized local files, and the internationalization of the backend is difficult to unify processing; it may be said that the front and back of the international chant, This scheme bloggers really thought about, but thought to maintain two sets of resources files, decisively give up. Finally decided to maintain a set of direct, do the front-end internationalization good. So in the online search based on the internationalization of jquery, the same, almost all say is jquery + jquery.i18n.properties This scheme, since we all so selection, the blogger also follow this idea to do a good job.

In the process of implementation, there are a lot of things to pay attention to and share, write a pits note here, hope to help everyone! Next, the blogger will step by step to lead you to solve the process of some of the pits, if there is the need for children's shoes can be concerned about, you may also encounter these problems.

Original address of this article: http://www.cnblogs.com/landeanfen/p/7581609.html

One, jquery.i18n.properties general solution

About the use of jquery.i18n.properties, many online materials, more complete use can refer to this article, there are more detailed instructions for use. Here Bo Master Simple overview of the next process.

1. js file to be referenced

First, add the following directory structure to your project file

The first page refers to the JS file as follows

<Scriptsrc= "~/scripts/jquery-1.9.1.min.js"></Script>    <Scriptsrc= "~/content/i18n/jquery.i18n.properties.js"></Script>    <Scriptsrc= "~/content/i18n/language.extensions.js"></Script>

where Jquery-1.9.1.min.js and jquery.i18n.properties.js files are open source components, you can find them directly online.

    • Jquery.i18n.properties.js
    • Jquery.js

The third file language.extensions.js is our custom JS file, if you write the internationalized code directly in the HTML page, this file is not used.

2. Initialization of HTML files and Internationalized components

Here directly to the code in the example above, first of all need a switch in English tags, such as a select

<SelectID= "Language">                <optionvalue= "ZH-CN">Chinese Simplified</option>                <optionvalue= "en">中文版</option>            </Select>

Then there are some HTML tags that look at the effect

< Div >    <  type= "Search"  class= "I18n-input"  selectname= " Searchplaceholder "  selectattr=" placeholder "></Div  >

Finally, we need to encapsulate the contents of the Language.extensions.js file, which has done the following several things:

    • When initializing the page, go to the current domain cookie to take the current browser to save the language of the cookie, according to the current language version to initialize the internationalization of the component, and then initialize the Select component of the selected value
    • Registers the Change event for the Select component, updates the language information in the cookie based on the currently selected language, and then refreshes the page.

The contents of this file will not be shown here, you can refer to the use of the above example article

3. Preparation of resource files

According to the above table of contents can be seen, we intend to put different language resource files in different languages of the folder inside, here for the moment, all the language resources into a file common.properties inside, such as the following:

En/common.properties

searchplaceholder= Pleaseinput serach informationsignout=Login outstation= Station  PartNo= partnodescription=descriptionquery=querypleaseselect=  Please selectadd=Addedit=EditDelete=delete

Zh-cn/common.properties

searchplaceholder= Please enter the keyword signout= exitstation = site partno=  Part Number Description= descriptionquery = query Pleaseselect= Please select Add= add = Edit Delete = Remove

Looks like it's done! You will find a cross-domain problem when you run down the source directly in Google Chrome.

Requires you to access the. Properties file in a webserver, which you only need to run with any kind of webserver, such as IIS, Apache, node's Web server, and so on. The blogger's code runs in Visual Studio, so it's based on IIS, and the first question comes when you move the code into vs.

Two, Pit one: Configure IIS support for. properties files

If this article is just the above content, it is meaningless. Next is the focus of this article to introduce!

Move the above code directly to vs inside, you will find the first question when running:

Why is there a request for three properties files here? Because the Jquery.i18n.properties.js component supports three types of naming, many articles are described, and when the component code runs, it requests the properties of three rules, so long as any one of the rules is found, it can be read into the contents. According to the list of documents given by the blogger above

According to this directory, we should be able to access zh-cn/by http://localhost:12770/Content/i18n/zh-CN/common.properties this URL. Common.properties this file, but the actual situation is true:

For this IIS error 404 problem, C # Programmer is certainly not unfamiliar, there are no more than two reasons:

    1. URL is not correct, this directory does not find this resource file
    2. Type of file IIS is not supported by default and denies requests directly

Excluding the first reason, it is only possible for the second cause. So how do we deal with it, searching the web for half-day data to find a solution:

This can really bypass the IIS file name verification, but change the source code is not a good solution, Bo Master has 1000 reasons to explain the shortcomings of the source code. This was certainly not the best solution, so the blogger decided to make a way.

Remember when the blogger learned less, IIS is not supported by default, so we add the following configuration in Web. config:

This is absolutely the same type of problem, plus this configuration is explicitly tell IIS, our system inside of some kind of suffix of the file need to Processer (processor or processing component) to deal with, inspired by this, So is the 404 problem with our. properties file available in this way? If we need to solve this problem, The first problem is the need to find the. properties file of the mimetype, bloggers think, since it is in JS inside call this. properties file, then we can use the JavaScript processing mechanism to handle the. properties file, taking into account the kind of above will all. Prop Erties replaced by. js, it seems. The properties and. JS have many similarities, so we add the following configuration:

Get results:

The test succeeds, it is so simple. Of course, if you publish to IIS, you may need to add the. Properties to the MIME type of IIS. This type of mapping.

Well, the problem is so pleasant to solve. If your webserver is not based on IIS, there may not be this problem, but I think the idea may be interlinked for reference!

Third, pit two: Use the HTML Data property to initialize internationalized content

In general, we need to use $ (' #id ') if we want to internationalize the contents of our tags . Text ($.i18n.prop (' proname ')); to assign a value to a tag, now the problem is, we develop an interface, there are many places need to do internationalization , we can not do this every page each label by this way to assign value it, so the workload is not a bit big, so Bo main thought, there is a better general solution to these needs to do the internationalization of the label unified Assignment it. The HTML Data property seems to be a good choice! It has the advantages of strong readability, maintainability, and the data () method compatible with jquery. For example, we modify the internationalization of the components of the following methods:

jQuery.i18n.properties ({Name: ' Common ', Path:'/content/i18n/' + i18nlanguage + '/',//Resource file pathMode: ' Map ',//use the values in the resource file in map modeLanguage:i18nlanguage, Callback:function() {//setting the display after a successful loadConsole.log ("i18n assignment ..."); Try {                //Initializing page elements$ (' [Data-i18n-placeholder] '). each (function () {                    $( This). attr (' placeholder ', $.i18n.prop ($ ( This). Data (' I18n-placeholder ')));                }); $(' [Data-i18n-text] '). each (function () {                    //if there is HTML in text that needs to be filtered out                    varHTML = $ ( This). html (); varReg =/< (. *) >/; if(reg.test (HTML)) {varHtmlvalue = reg.exec (HTML) [0]; $( This). html (Htmlvalue + $.i18n.prop ($ ( This). Data (' I18n-text '))); }                    Else {                        $( This). Text ($.i18n.prop ($ ( This). Data (' I18n-text ')));                }                }); $(' [Data-i18n-value] '). each (function () {                    $( This). Val ($.i18n.prop ($ ( This). Data (' I18n-value ')));            }); }            Catch(ex) {} console.log ("I18n Write Complete"); }    });

Using the Data property to get the label, and then for each label through the corresponding data-i18n-property for internationalization assignment, here temporarily defined three types of Data-i18n-placeholder, Data-i18n-text, The Data-i18n-value property, if there are other requirements, can be added to other types.

And then look at the use of our HTML page

<class= "Typeahead"  type= "text"  ID= "Menu_search "=" Searchplaceholder "/>
<data-i18n-text= "setting"></span> 

This allows you to internationalize your labels without having to write a tag's assignment code.

Iv. Pit III: Internationalization of third-party components (i)

For third-party components, the Chinese in our custom code is internationalized, and I just need to use $.i18n.prop (' key '), such as bootstraptable:

{        ' auditeventtype ',        ' business type ',        ' 12% '}

Direct use

{        ' auditeventtype ',        title: $.i18n.prop (' Blltype '),        ' 12% '} 

Can. This solution is very simple, there is nothing to say, but there are some third-party components, they have the internationalization of the function, the initialization of the need to specify the type of internationalization, shape such as:

$ (". Date"). DateTimePicker ({     ' yyyy-mm-dd ',// date format, display only date     locale: ' ZH-CN '      // Chinese Culture });

The solution currently in mind is to explicitly assign a value based on the current language stored in the cookie

// get the language inside the cookie var userlanguage = Getlanguagecookie ("userlanguage"); $ (". Date"). DateTimePicker ({     ' Yyyy-mm-dd ',// date format, only show date     locale:userlanguage = = ' zh-cn '? ' Zh-cn ': ' en-US '     // internationalization });

If it is in multiple languages, it can be handled at the front end itself.

V. Pit IV: Internationalization of third-party components (ii)

The above describes the third-party component initialization when specifying internationalization, in addition, there is another situation, is that many components have their own localization (about internationalization and localization of the difference, please google) file, its internationalization is by referencing different localization JS file to achieve, For example, Bo main bootstraptable components, its directory:

There are other components as well, such as:

So in response to this situation, our internationalization of how to achieve, here is the idea of Bo Master is the dynamic reference JS, through the current cookie in the language of the type to refer to the corresponding language of the JS file, for example, for bootstraptable, we go to the dynamic reference JS

//The component introduces JS according to the internationalization dynamicvarUserlanguage = Getlanguagecookie ("Userlanguage"); //If there is no cookie, the default value is used        if(!userlanguage) {Userlanguage= ' ZH-CN '; }        if(Userlanguage = = ' ZH-CN ') {            varScript = $ (' <script><\/script> ')); Script.attr (' src ', '/content/bootstrap-table/locale/bootstrap-table-zh-cn.js '); $(' Body '). append (script); }        Else if(userlanguage = = ' en ') {            varScript = $ (' <script><\/script> ')); Script.attr (' src ', '/content/bootstrap-table/locale/bootstrap-table-en-us.js '); $(' Body '). append (script); }

If you want to write a more elegant code, you can implement the front-end of the abstract factory, here is just a way to realize the idea.

Vi. Summary

Ruled out the difficulties of the above steps, our internationalization in the project is basically able to run normally, as for WEBAPI inside the return message of the Chinese, if you want to do internationalization, we can by the return message encapsulated, unified return to the front-end processing. This article "Pits Way" may not be the best, but at least to provide you with a realization of ideas, if you have a better way to achieve, welcome message exchange. If you feel that this article can help you, you can freely play the blogger on the right.

Original source of this article: http://www.cnblogs.com/landeanfen/

Welcome to reprint, but without the author's consent, reprint article must be in the article page obvious location to the author and the original link , otherwise reserve the right to pursue legal responsibility

Front End Series--jquery front-end internationalization solution "pits Diary"

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.