Monday, January 12, 2009

Internationalization for javascript on top of a Java web application

In a Java web application, the i18n is usually handled by using resource bundles. When using javascript, you could use something resource bundle alike like dojo suggests but then you need to make the properties files available to the browser and for every page, all translations are loaded. I would rather like to keep using the resource bundles that I know and have tools to edit for in both my jsp's and javascript.

For this end, I have written a small tag that reads the translations you need and puts them in a small JSON object. The tag currently looks like this (I only use it in one application thus customization is not yet an issue):

public class ResourceToJavaScriptTag extends TagSupport {
/**
* Only the keys starting with this filter will be added to the bundle.
* Also this starting part of the key will be removed (making JSON attributes easier to access).
*/
private String filter = "";
/**
* The name of the bundle.
*/
private String name = "";

@Override
public int doStartTag() throws JspException {
try {
StringBuilder bundle = new StringBuilder();
bundle.append("");
pageContext.getOut().print(bundle);
} catch (Exception ex) {
throw new JspTagException("ResourceToJavaScriptTag: " +
ex.getMessage());
}
return SKIP_BODY;
}

@Override
public int doEndTag() {
return EVAL_PAGE;
}

public void setFilter(String filter){
this.filter = filter;
}

public String getFilter(){
return filter;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


The filter is determines which translations to select. Only the keys starting with this filter will be added to the object. The name is the name of the javascript object containing the translations.
The tag <tags:i18n filter="my.translations" name="myBundle"> gives me:
<script type="text/javascript">var myBundle = {"trans1":"my translation1","trans2":"my translation2"}</script>
for the properties
my.translations.trans1=my translation1
my.translations.trans2=my translation2
your.translations.trans3=your translation3

As you can see, only the keys starting with my.translations are added to the json object. Now we can get a translation as myBundle.trans1.

1 reacties:

indiroma said...

Thanks for the sharing this website. it is very useful professional knowledge. Great idea you know about company background.
web application development

 
The opinions expressed in this blog are those of Jeroen Wyseur and may not reflect the opinion of his employer or any customer of said employer.