Skip to content

Handling flag selection

kristianmandrup edited this page May 14, 2012 · 1 revision

Here is an example of setting up a flag click handler in order to call the server with the selection of the flag.

$("li.flag").click(function() {
  country = $(this).data('locale'); # or use one of the other data attribute codes of the .flag element

  // async post
  $.post("/locale/select", { "country": country }, function(data) {
    console.log(data);
  });	
});

WorldFlagsUrlHelper

The WorldFlags engine comes with a javascript object WorldFlagsUrlHelper. To use it, add the following to your application.js manifest file.

//= require world_flags/url_helper

WorldFlagsUrlHelper has the following public API methods:

  • reloadWithLocaleParam(locale)
  • addLocaleParameter(url, locale)
  • addUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)

Fx WorldFlagsUrlHelper.addUrlParameter(url, 'locale', locale, true); or WorldFlagsUrlHelper.addLocaleParameter(window.location.href, locale);

It most cases use of reloadWithLocaleParam is sufficient and can be used like this:

$("li.flag").click(function() {
  country = $(this).data('locale');

  // full page reload with locale=xx param added to url :)
  WorldFlagsUrlHelper.reloadWithLocaleParam(country);
});
Clone this wiki locally