简体   繁体   中英

Handling i18n in javascript files

For example, my app relies heavily on the use of AJAX when doing CRUD operation.

As of now, messages are hardcoded similar to this.

function handleSaveNewMember(xhr, status, args) {  
    if(args.validationFailed || !args.result) {   
    }else{  
        showmsg.show([{summary:'Add New Member', detail: 'Successfully Added New Member', severity: 'info'}]);
    }  
}

But what if you deploy your app to a different locale? Then how do you handle the i18n feature?

I used Primefaces here by the way.

It may not be the best solution, but in the past I've essentially linked a js file that contains string constants that I reference in code. On load, I load the appropriate js file for the current culture. Make sure to have some kind of defaults for each constant should that file not load though.

If you are allowed to use JQuery - we are using this nice little plugin in our project for i18n -

http://code.google.com/p/jquery-i18n-properties/

Fits our needs well..

Another way is to iterate over you properties file and populate it into a HashMap say mapOfLabels then turn into a Json string with Gson gson.toJson(mapOfLabels);

than place the Json string into a bean variable that will be "linked" via getter to your xhtml page like this

<h:inputText id="locLabelsID" value="#{myBean.locLabelsField}" styleClass="hide"/>

and in js side you can simply access it and parse it with jQuery like this :

var myJsonVar= $("#locLabelsID").val();
locLabels = $.parseJSON(myJsonVar); 

and access it with your label key like this

locLabels[key];

of course the init of the hash map is being done only once and same goes for the init in the js side...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM