rmariuzzo / lang.js Goto Github PK
View Code? Open in Web Editor NEW:performing_arts: Laravel Translator class in JavaScript!
License: MIT License
:performing_arts: Laravel Translator class in JavaScript!
License: MIT License
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).
We want to implement both getter and setter methods to interact with the “fallback”:
getFallback
— return the fallback locale (see Laravel's API).setFallback
— set the fallback locale (see Laravel's API).Also, we want to take in account of the fallback
value when executing get()
, trans()
and choice()
.
Tests needs to be created to cover the fallback feature.
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
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
As a user, I would like to have a trans
method that implement Illuminate/Translation/Translator#trans
method.
This method should be an alias to get()
method.
The test/spec/lang_trans_spec.js
should be created and has to fully cover all cases of trans
method.
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.
We need to add into README
file a documentation section or note on how to get a message that originally was in a nested directory (that's using the /
). For example:
Lang.get('forum/thread.hello')
The documentation should be added inside the code block here: https://github.com/rmariuzzo/Lang.js#get
As a user, I would like to have a choice
method that implement Illuminate/Translation/Translator#choice
method.
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
.
The test/spec/lang_choice_spec.js
should fully cover all cases of choice
method.
As a user, I would like to have a get
method that implement Illuminate/Translation/Translator#get
method.
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
.
The test/spec/lang_get_spec.js
should fully cover all cases of get
method.
As a user, I would like to have a has
method that implement Illuminate/Translation/Translator#has
method.
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.
The test/spec/lang_has_spec.js
should fully cover all cases of has
method.
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
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.
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.
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);
}
Line 297 in 1d8e091
If we have an empty value for a given key in a fallback locale:
'button.tooltip' => ''
and we request Lang.get('button.tooltip') then _getMessage returns 'button.tooltip'.
if (message[subKey] !== undefined) {
solves the problem.
Hey guys.
Is There an option the load the messages from a remote json?
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.
We want to add full documentation in the README.md
file. The objectives are:
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"
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.
git clone https://github.com/rmariuzzo/Lang.js
git checkout develop
npm run test
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"
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')})?
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.
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
}
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')
});
As a user, I would like to have a transChoice
method that implement Illuminate/Translation/Translator#transChoice
method.
This method should be an alias to choice()
method.
The test/spec/lang_transChoice_spec.js
should be created and has to fully cover all cases of transChoice
method.
Original reporter: rmariuzzo/Laravel-JS-Localization#119
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
Hi There,
Thanks for the great package, is there a way to prevent escaping of html?
Thank you
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.
Line 288 in 31474a8
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'
Laravel 5.4 introduces the asterisk symbol for defining the infinity of a pluralization string (instead of «Inf») which gets ignored by Lang.js.
See https://laravel.com/docs/5.4/localization#pluralization and rmariuzzo/Laravel-JS-Localization#99
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.