Wednesday, August 5, 2009

Setting GWT locale using cookies

GWT represents locale as a client property whose value can be set either using a meta tag embedded in the host page or in the query string of the host page's URL.
I wanted to set the locale of my GWT application stored somewhere, so that I don't need to always append ?locale=ja or &locale=ja to the URL for every page on the site. Putting the meta tag every time the page is requested is also not an option, since you still need to let the server know the preferences of the user (session management).
For example, if I have http://www.ngambek.com/ page in Indonesian, but I want to set it to Japanese, I need to set the address to http://www.ngambek.com/?locale=ja to let the GWT system use the Japanese version of the page. Later when there is a link to http://www.ngambek.com/12345678, I would need to make it http://www.ngambek.com/12345678?locale=ja. What a burden.
I decided to use cookie to store the preferred locale, then let a javascript snippet run to set a meta tag dynamically. When the GWT module is loaded, the locale will be detected because the appropriate meta tag will have been written (in browser's memory).
So, before the GWT module script is loaded, I put these lines onto the HTML file:
var getCookie = function(c_name) {
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length+1;
      c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

var locale = getCookie("locale");
if (! locale) {
  locale = "id";
}

document.write("<meta name='gwt:property' content='locale=" + locale + "' />");
Then, in order to set the locale, it's just a matter of setting the locale cookie and reloading the page:
function setLocale(locale) {
  document.cookie = "locale=" + escape(locale);
  document.location.href = document.location.href;
}
By the way, the internationalization feature of GWT is great! Try it if you haven't tried it before.

4 comments:

  1. Thank for posting this. I needed to implement something similar, and this saved me a lot of time!

    ReplyDelete
  2. Thank you so much. Your recipe helped me to integrate multi-language GWT app with Magnolia CMS smoothly.

    ReplyDelete
  3. Thanks, this is really helpful. I'd like to contribute my code for setting the local, which I implemented in GWT. It also verifies the current locale (to avoid senseless page reloading if the user miss-clicks). The cookie is stored for 30 days:

    if(!LocaleInfo.getCurrentLocale().getLocaleName().equalsIgnoreCase("en")) {
    Date date = new Date();
    long currentTime = date.getTime();
    date.setTime(currentTime + 2592000000L);
    Cookies.setCookie("locale", "en", date);
    Window.Location.reload();
    }

    ReplyDelete