Code Monkey home page Code Monkey logo

lang.js's Issues

Implement fallback

Summary

As a user, if I try to get('welcome') with the locale set to ‘es’ and there's no message in Spanish (es) but it exists in English (en) then I would like the get method to return the message in the “fallback” locale (in this case English).

Description

We want to implement both getter and setter methods to interact with the “fallback”:

Also, we want to take in account of the fallback value when executing get(), trans() and choice().

Tests

Tests needs to be created to cover the fallback feature.

Vue.js support?

Is it possible to use this plugin with Vue.js?

I got it to work as prototype and display the current language but won't get it to work reactive.

import Lang from 'lang.js'
import messages from './messages'
import { Vue } from './../bootstrap'

const lang = new Lang({
    messages: messages,
    locale: 'en',
    fallback: 'en'
});

Vue.prototype.lang = lang

Lang.choice with fallback uses wrong plural form

When using fallback for translation, choice still uses the current locale for pluralForm, causing wrong rule being used.

> Lang.messages['en.test'] = ':count box|:count boxes'
> Lang.setFallback('en')
> Lang.setLocale('pl')
> Lang.choice('test', 1)
"1 box"
> Lang.choice('test', 2)
"2 boxes"
> Lang.choice('test', 10)
undefined

Is it possible to access all keys from a lang file?

Thanks for your great work on this @rmariuzzo!

I'm wondering, is it possible to access all the keys in a given lang file? For example, say I have a lang file called person-questions and it contains things like :

	"name" => "What is your name?",
	"age" => "How old are you?",
	"hobbies" => "What are your hobbies?"

Is there a way, using Lang.js to grab a list of the keys, getting an array of values like ['name', 'age', 'hobbies']?

The use case is that I'd like to populate a select menu with options, and I'd like to always include every string from a certain lang file. Thanks.

Implement `choice` method

Summary

As a user, I would like to have a choice method that implement Illuminate/Translation/Translator#choice method.

Description

The method should accept 4 arguments:

  • key — a string indicating the translation key.
  • number — a number value indicating something quantifiable.
  • replace — an object of replacements values. Example: { key1: 'value1', key2: 'value2' }.
  • locale — a string indicating the locale to use. This should be optional, when not set, use getLocale().

The method will return a localised string for the given key if found, otherwise the given key.

Tests

The test/spec/lang_choice_spec.js should fully cover all cases of choice method.

Implement `get` method

Summary

As a user, I would like to have a get method that implement Illuminate/Translation/Translator#get method.

Description

The method should accept 3 arguments: key, replacements and locale.

  • key — a string indicating the translation key.
  • replace — an object of replacements values. Example: { key1: 'value1', key2: 'value2' }.
  • locale — a string indicating the locale to use. This should be optional, when not set, use getLocale().

The method will return a localised string for the given key if found, otherwise the given key.

Tests

The test/spec/lang_get_spec.js should fully cover all cases of get method.

options is not defined

Since the newest release I always get this error:

image

Has anyone an idea?

I'll will check it as soon as i can.

Implement `has` method.

Summary

As a user, I would like to have a has method that implement Illuminate/Translation/Translator#has method.

Description

The method should accept 2 arguments: key and locale. The last one should be optional, when not set, use getLocale(). The method will return a boolean value, true if the given key exists with the provided or default locale, otherwise false will be returned.

Tests

The test/spec/lang_has_spec.js should fully cover all cases of has method.

Multiple files, not only one

Hello,

I use Laravel and VueJS and would like to offer my site in different languages. To make it uncomplicated to translate the page, I would like to have different files and not just one.

Currently, it looks like this:
module.exports = { "en.auth": { "failed":"These credentials do not match our records :name.", "throttle":"Too many login attempts. Please try again in :seconds seconds." }, "de.auth": { "failed":"These credentials do not match our records :name.", "throttle":"Too many login attempts. Please try again in :seconds seconds." }, "es.auth": { "failed":"These credentials do not match our records :name.", "throttle":"Too many login attempts. Please try again in :seconds seconds." }, }

I would like to have different files like en.js, de,js and es.js.

Meine app.js sieht wie folgt aus:
/* Laravel VueJS Translation */ require('lang.js'); import VueLang from '@eli5/vue-lang-js' import translations from '../lang/en'; Vue.use(VueLang, { messages: translations, // locale: 'en', // Set locale fallback: 'en' // Set fallback lacale });

Do you have any idea how I split a file to three or more? With if, elseif and else it somehow doesn't work. :(

Thanks for your help!

Kind regards,
Tyler

Capitalize place-holders

Laravel Translator API support capitalizing translated values. The docs explains:

If your place-holder contains all capital letters, or only has its first letter capitalized, the translated value will be capitalized accordingly:

'welcome' => 'Welcome, :NAME', // Welcome, DAYLE
'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle

We should support this fancy feature.

Not proper translations [locale:strings] for EN locale

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);
    }

HTML lang attribute to auto-setLocale

Why to manually enforce the default locale:

Example:
<script type="text/javascript"> Lang.setLocale('{{App::getLocale()}}'); </script>

While everyone has the locale defined as an html attribute: lang?

Example:
<html lang="el">

It would be great to automatically check the lang attribute of the html tag to preset the default locale.

Create documentation

We want to add full documentation in the README.md file. The objectives are:

  • How to use? (initialization, messages format)
  • Cover all methods with examples.

Fallback is not working

Take Your own example

var lang = new Lang({
    messages: {
        'en.greetings': {
            'hi': 'Hi',
            'hello': 'Hello'
        },
        'it.greetings': {
            'hi': 'Salve'
        }
    }
});

lang.setLocale('it');
lang.get('greetings.hello');
// > "greetings.hello"

lang.setFallback('en');
lang.get('greetings.hello');
// > "greetings.hello" instead of "Hello"

Support dot in localized keys

This issue was originally reported at: rmariuzzo/Laravel-JS-Localization#115 by @ERPedersen.

The following test will not work:

it('should return the expected message if the key has a dot', function() {
  expect(lang.get('messages.dot.in.key')).toBe('Dot In Key');
})

By default, Lang.js interpret . as separators. Therefore, we would to detect if a key exist with the dot.

Steps to reproduce

  1. git clone https://github.com/rmariuzzo/Lang.js
  2. git checkout develop
  3. npm run test

Tasks

  • Support simple dot key.
  • Support nested dot key.
  • Support tricky dot key.

Fallback language not work

I tried the following code from README.md. However, the fallback "en" locale does not work, with both lang.get('greetings.hello') in the following code returns greetings.hello.

var lang = new Lang({
    messages: {
        'en.greetings': {
            'hi': 'Hi',
            'hello': 'Hello'
        },
        'it.greetings': {
            'hi': 'Salve'
        }
    }
});

lang.setLocale('it');
lang.get('greetings.hello');
// > "greetings.hello"

lang.setFallback('en');
lang.get('greetings.hello');
// > "Hello"

translation attributes

Is there a way to use the 'attribues' array, which is defined in a translation file. E.g. 'email' => 'Email address'. or will I simply have to do something like Lang.get('validation.email', {attribute: Lang.get('validation.attributes.email')})?

Does it even work with JSON object messages?

I tried:

{
    "en": {"Yes": "Yes", "No": "No"}},
    "de": {"Yes": "Ja", "No": "Nein"}}
}
window.Lang.setMessages({
    'en': en,
    'de': de,
});

It parses keys to be flattened like this: de.No and then, of course, it cannot find the key.

Then I flattened my messages object to be so:

{
    "en.Yes": "Yes", 
    "en.No": "No", 
    "de.Yes": "Ja",
    "de.No": "Nein",
}
window.Lang.setMessages({
    'en': en,
    'de': de,
});

and it worked.

What is the point of this approach? Why would I need to loop through all my language keys and flatten them?

Since Laravel provided us JSON translations, you should make a configuration option for that.

    Lang.prototype._getMessage = function(key, locale) {
        locale = locale || this.getLocale();

        if (this.messages[locale] === undefined) {
            locale = this.getFallback();
        }

        if (this.messages[locale][key] === undefined) {
            locale = this.getFallback();
        }

        if (this.messages[locale][key] === undefined) {
            return null;
        }

        return this.messages[locale][key];
    }

I believe the code above is pretty self-explanatory.

AMD module support

Hi.

I kinda cannot get your package to work, maybe you can help me.

When I do

var Lang = require('lang.js')

var lang = new Lang({
    messages: {
        "en.foo": {
            bar: 'baz'
        },
        "pl.foo": {
            bar: 'quz'
        }
    },
    locale: 'pl',
    fallback: 'en'
})

I get an error saying

Uncaught TypeError: Lang is not a constructor

Same thing happens when I replace require with import:

import Lang from 'lang.js';

After import/require the Lang object looks like this:

{
    locale: "en", 
    fallback: undefined, 
    messages: undefined
}

Setup

Dependencies

{
    "gulp": "^3.9.1",
    "gulp-shell": "^0.5.2",
    "jquery": "^3.1.0",
    "lang.js": "^1.1.1",
    "laravel-echo": "^1.1.0",
    "laravel-elixir": "^6.0.0-11",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    // and other like Vue or Moment.js    
}

gulpfile.js

const elixir = require('laravel-elixir');
const shell = require('gulp-shell');

require('laravel-elixir-vue-2');

var Task = elixir.Task;
elixir.extend('langjs', function(path) {
    new Task('langjs', function() {
        gulp.src('').pipe(shell('php artisan lang:js resources/assets/js/messages.js'));
    });
});

elixir(mix => {
    mix.sass('app.scss')
        .langjs()
        .webpack('app.js')

});

Support for LCID strings (en_us/en-us) on plural forms

Hi,

Is it possible to support LCID strings for the plural forms? we make use of en_us and en_ca rather than the en form, which poses problems when wanting to access the file we want, as getPluralForms function in the util.ts only supports the language codes.

Unless there is an alternative we can employ to circumvent that?

Many thanks

Prevent escaping of HTML

Hi There,

Thanks for the great package, is there a way to prevent escaping of html?

Thank you

Returning array

It would be nice if defining an array as an translation value would be possible. It'S possible inside laravel itself and im using it for this purpose.
If i define a value in Lang.js though it returns the key instead of the array.

Incorrect returned value

if (message[subKey] !== undefined) {

if we have two lines as

    'book.btn.finish'               => 'Finish Booking',
    'book.btn'                        => 'Book Now',

and request Lang.get('book.btn.finish') then _getMessage returned 'Book Now'

Add JsHint

We would like to have a task that run JsHint against all JS source code (including test specs), something like: npm run jshint.

Also, we should run JsHint when running: npm run build:dist too to ensure our code is JsHint'ed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.