Páginas

Thursday, February 3, 2011

jQuery-UI datepicker dynamic internationalization in Rails

The jQuery UI datepicker is internationalizable, by chosing from one of the languages in the regional array, as such:

$(selector).datepicker($.datepicker.regional['en-GB']);

As is easy to see, this changes the datepicker language to english. In order for any other language, apart from english (which is the default), to work, we need to include a javascript file that defines the strings to be shown.

We can either include all the languages (http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/i18n/jquery-ui-i18n.min.js), or just the ones we need, that can be found here.

So far so good. But what if we want to include only the file we need, according to the system's locale?

It's pretty simple, and it prevents a user from having to download files he is not going to use, but just the one for the language he is viewing the site.

First, you'll have to create a helper that checks the current locale and includes the file accordingly, so it can be called from the views that use the datepicker.


def include_i18n_calendar_javascript
  content_for :head do
    javascript_include_tag case I18n.locale
      when :en then "jquery.ui.datepicker-en-GB.js"
      when :pt then "jquery.ui.datepicker-pt-BR.js"
      else raise ArgumentError, "Locale error"
    end
  end
end


As you can see, this has a case that chooses the file according to the locale, an returns it to the javascript_include_tag helper that generates the HTML for the inclusion of a javascript file and places it in the header with the content_for helper.

Now you only have to call the helper in the view and add some javascript.

var counter = 0;
var locale = "
for(i in $.datepicker.regional){
  if(counter == 1)
  { locale=i; break; }
  counter++;
}


Because the regional array is not exactly an array, but an hash (or an associative array, in javascript terms), we will have to iterate through each of it's objects. The one we want is the second, that the reason for the break. This object is the string the key in that associative array for the definitions of the locale we want. In the case of the first example, it would be "en-GB".

Now, we just initialize the datepicker with this variable:


$.datepicker.setDefaults( $.datepicker.regional[ '' ] );
$( ".datepicker" ).datepicker($.datepicker.regional[locale]);


And that's it. Now your datepickers are internationalized in a dynamic way.

PS: Of course you'll need a textfield that has the HTML class datepicker (or any other you choose).

No comments: