airbnb / polyglot.js

Give your JavaScript the ability to speak many languages.
http://airbnb.github.io/polyglot.js
BSD 2-Clause "Simplified" License
3.71k stars 208 forks source link

Return false when a translation is not found and allowMissing is set to false #34

Closed limoragni closed 8 years ago

limoragni commented 9 years ago

I'm using polyglot for translating dynamically generated strings and I would like to have a way of knowing when a translation is not available.

For what I saw in the code the allowMissing just pass the string to the choosePluralForm and interpolate methods. But if allowMissing is false, it just returns the key used for the translation. The keys I'm using are in some cases numerical codes that refers to strings in different languages, so having the key back breaks my code silently.

   if (typeof this.phrases[key] === 'string') {
      phrase = this.phrases[key];
    } else if (typeof options._ === 'string') {
      phrase = options._;
    } else if (this.allowMissing) {
      phrase = key;
    } else {
      this.warn('Missing translation for key: "'+key+'"');
      result = key;
    }
    if (typeof phrase === 'string') {
      options = clone(options);
      result = choosePluralForm(phrase, this.currentLocale, options.smart_count);
      result = interpolate(result, options);
    }
    return result;

Apart for the warning I think that result should be false. What do you think?

ljharb commented 8 years ago

That seems reasonable, but would be a breaking change. What about adding an alternative option that returns undefined or false or something?

limoragni commented 8 years ago

An option like allowMissing but returning false/undefined when there is no matches? I think that would be enough.

pleivac commented 8 years ago

Is there any way to achieve this? I'm thinking something like if(polyglot.t("key") === "key") the translation doesn't exists. But this solution is really ugly, and not work all the time for me.

ljharb commented 8 years ago

@pleivac you can use polyglot.has(key) to determine if the phrase is present or not.

pleivac commented 8 years ago

Perfect @ljharb... Many many thanks!

ljharb commented 8 years ago

@limoragni @pleivac I've filed #77 to address this in a more generic manner. Please let me know if that will resolve your use cases.

limoragni commented 8 years ago

@ljharb yes, I think onMissingKey is a great solution!