Thursday, February 20, 2014

I18next, Polymer and Pluralization

Up tonight, I am eager to try some of the i18next internationalization features in Polymer. There are many supported features in i18next, but tonight I am going to stick with pluralization and dates as I've tried them previously with the Dart version of Polymer.

I already have a spot for pluralization in my <hello-you> Polymer, so I start there. From the template, the countMessage bound variable needs to be pluralized:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-you" attributes="locale">
      <!-- [l10n] how_many -->
      <input value="{{count}}">
      <!-- [l10n] done -->
      <input type=submit value="{{done}}!" on-click="{{updateCount}}">
      <!-- updated when updateCount() is invoked -->
    <script src="../bower_components/i18next/i18next.js"></script>
  <script src="hello_you.js"></script>
After last night, some of the bound variables in there are already being localized via i18next with simple labels (how_many and done). That results in:

Tonight, I would like to figure out how to move beyond that—to get the updateCount() method to perform some translation.

I start in the translation.json from last night. In there, I add some keys for balloon—I will count the number of red balloons that I have:
  "app": {
    "hello": "Hello",
    "done": "Done",
    "how_many": "How many?",
    "instructions": "Introduce yourself for an amazing personalized experience!"
  "balloon": "I have one red balloon.",
  "balloon_plural": "I have __count__ red balloons."
The double underscore is how i18next indicates variable interpolation. In this case, if the supplied count is not one (i.e. it is plural), then the number will be interpolated into the second message.

To make that happen from the <hello-you> Polymer, I need the updateCount() method to invoke the appropriate i18next translation:
Polymer('hello-you', {
  // ...
  updateCount: function() {
    this.count_message = i18n.t("balloon", { count: parseInt(this.count, 10) });

That works with one red balloon:

Or two red balloons:

Or even 99 red balloons:

After reading the documentation a bit, it seems that i18next defers Dates to other libraries. I cannot say that I blame it since dates in JavaScript are notoriously awful. Still, that is a bit of a letdown keeping me from using this as a one-stop shop for my i18n needs. Even so, the pluralization is definitely nice.

Day #1,032

No comments:

Post a Comment