rmariuzzo / Lang.js

:performing_arts: Laravel Translator class in JavaScript!
MIT License
260 stars 62 forks source link

Not proper translations [locale:strings] for EN locale #92

Open MitichPavel opened 11 months ago

MitichPavel commented 11 months ago

Laravel-JS-Localization generated translations issue

If in folder lang are translations in json files, translations generated by Laravel-JS-Localization looks like:

{
   "pl:strings": {
      "English key string": "Polish value string"
   }
}

In this case in Laravel provide helper function __ and as a default value it returns passed argument string. Example:

  lang.setLocale('pl');
  lang.get('English key string') // return ==> 'English key string'

  lang.get('strings.English key string') // return ==> 'Polish value string'

  // but if now we set locale to default 'en'
  lang.setLocale('en');
  lang.get('strings.English key string') // return ==> 'strings.English key string'

In folder we have only resources/lang/pl.json because default behavior of Laravel function return key as default value.

Possible solution

Add aditional method __ for getting translations generated by Laravel-JS-Localization.

    /**
     * Get a translation message wrapper function for getting JSON Laravel-JS-Localization generated translations 
     *
     * @param key {string} The key of the message.
     * @param replacements {object} The replacements to be done in the message.
     * @param locale {string} The locale to use, if not passed use the default locale.
     *
     * @return {string} The translation message, if not found the given key.
     */

    Lang.prototype.__ = function(key, replacements, locale) {
        const stringsDomain = "strings";
        const stringsKey = `${stringsDomain}.${key}`;
        const stringTranslation = this.has(stringsKey, locale);
        const translation = this.has(key, locale);

        if (!stringTranslation && !translation) {
            return key;
        }

        if (translation) {
            return this.get(key, replacements, locale);
        }

        return this.get(stringsKey, replacements, locale);
    }
MitichPavel commented 11 months ago

@rmariuzzo :wave: