Translate custom attributes with i18next (placeholder, value)

Salvador Dali picture Salvador Dali · Mar 29, 2014 · Viewed 20.2k times · Source

I am investigating what is possible with i18next localization library.

Right now I have the following code (full Fiddle is here):

HTML

<div data-i18n="title"></div>
<input placeholder="Hello" value="name">
<div class="holder"></div>
<button class="lang" data-lang="en">Eng</button>
<button class="lang" data-lang="ch">Chi</button>

JS

$(document).ready(function () {
    i18n.init({
        "lng": 'en',
        "resStore": resources,
        "fallbackLng" : 'en'
    }, function (t) {
        $(document).i18n();
    });

    $('.lang').click(function () {
        var lang = $(this).attr('data-lang');
        i18n.init({
            lng: lang
        }, function (t) {
            $(document).i18n();
        });
    });
});

It translates all text elements, but the problem is that I can not translate custom attributes. For example text inside the div is translated, but I can not understand how can I translate custom attributes like placeholder and value.

Another problem is with my way of translation. Whenever a button Chi, Eng is clicked, I am initializing the translation (but I am not sure this is a correct way). Edit I think I found how to solve this problem (I need to use setLng): i18n.setLng(lang, function(t) { ... })

Answer

Salvador Dali picture Salvador Dali · Apr 2, 2014

After asking i18next creator this question directly, I received the following reply: all I need is to put my custom attribute in front of the translation element. Here is an example:

<div data-i18n="[title]titleTransl"></div>
<input data-i18n="[placeholder]placeTransl" value="name">

If multiple attributes are needed, separate them by a ;.

I learned 2 things by this:

  • I have to read better documentation.
  • 118next's creator is really helpful (this is a thank you remark for him).