Search code examples
javascriptjqueryinternationalizationwikimedia

JQuery.i18n replaces none existing key with the key name instead of the fallback text


I am referring to https://github.com/wikimedia/jquery.i18n#data-api in the JQuery.i18n documentation:

<li data-i18n="message-key">Fallback text</li>

It is also possible to have the above li node with fallback text already in place.

Unfortunately I don't get this work. When I don't have message-key in the language file then JQuery.i18n displays instead of Fallback text the key: message-key

My question:

What am I doing wrong? As soon I add the key to the language file then it gets replaced, so apparently the language file is loaded correctly and also the function calls seem to work.


Solution

  • It seems to be a bug! I was checking the JQuery.i18n code and I found the problem.

    It's all in jquery.i18n.js. It starts with this code in line #169:

    if ( message === '' ) {
       message = key;
    }
    

    The if is executed when there is no text defined for the key and then the message becomes the key.

    I commented the assignment:

    if ( message === '' ) {
       // message = key;
    }
    

    Then I had to change in line #244 this code:

    } else {
       $this.text( i18n.parse( messageKey ) );
    }
    

    to

    } else {
       const translatedText = i18n.parse( messageKey );
       if ( '' !== translatedText ) {
          $this.text( translatedText  );
       }
    }
    

    Now the fallback text does work. The following comment in line number 165 seems to confirm it's a bug and the developer knows it but somehow he lives with it:

            // FIXME: This changes the state of the I18N object,
            // should probably not change the 'this.parser' but just
            // pass it to the parser.
    

    If you apply this hack so consider also the modifications for html and other tags few lines above.