rmariuzzo / laravel-js-localization Goto Github PK
View Code? Open in Web Editor NEW🌐 Convert your Laravel messages and consume them in the front-end!
Home Page: https://github.com/rmariuzzo/laravel-js-localization
License: MIT License
🌐 Convert your Laravel messages and consume them in the front-end!
Home Page: https://github.com/rmariuzzo/laravel-js-localization
License: MIT License
It would be cool, if JS plugin would take current locale from HTML "lang" attribute. And if developer needs, he can call Lang.setLocale to override.
When I try to run php artisan lang:js
I get the Error in the title.
Solution:
The right name of the Method is generate()
not make()
https://github.com/rmariuzzo/Laravel-JS-Localization/blob/master/src/Mariuzzo/LaravelJsLocalization/Generators/LangJsGenerator.php#L41
Accept my Merge Request to fix this.
To simplify the development of this package, I have been thinking on separating the JS library from this Laravel Package. In the end we will have:
What do you think collaborators? @gpopoteur @xAockd @okaufmann
I'm starting a bigger project, so I have a lot to translate.
So I thought, why could we not use gulp to publish this?
And we could:
I used this package to extend gulp:
https://github.com/sun-zheng-an/gulp-shell
and in my gulpfile is use this:
var shell = require('gulp-shell');
//......
gulp.task('langJs', shell.task('php artisan lang:js -c public/js/messages.js'));
Maybe it could be mentioned in documentation or is it not useful? what do you think @rmariuzzo?
It so happens that I can't import the 'Lang' class in my Vue component; I receive a ReferenceError. Any help would be appreciated.
At the end of unit tests you can see:
OK (9 tests, 37 assertions)
> if [[ `php -v` =~ "PHP 5.6" ]]; then ./vendor/bin/phpunit --configuration tests/5.3; fi
sh: 1: [[: not found
I suppose that it's bash
syntax while CI using common sh
.
I need help! I'm generating the file via php artisan command and I include the generated js file that has all my messages and the library to my html page. I set the locals but when I try to get the message like so: Lang.get('messages.hello') it can't find the key.
What should I do now?
Maybe there should be some option to define default location of messages.js file?
For example if someone want to have it in public/js/messages.js
, he has to provide every time this localization in php artisan lang:js
What is composer test-install ? and composer test? (referenced in ReadMe)
Hello, do you have any plans to adapt to laravel 5.4? I was updating my system and found an error in LaravelJsLocalizationServiceProvider.php on line 67, I believe that is why the share method was removed in the latest version of laravel. Thanks!
Hi, I'm currently writing a tool that will help to find missing translations in the JavaScript-files. Just letting you know, https://github.com/clentfort/laravel-find-js-localizations. :) Would appreciate feedback.
It appears that translations in a resources/lang/en.json
file (used for translations keyed by the default text) are ignored by the generator.
We're facing a problem where we version assets based on their content to improve caching. We're compiling on 4 different servers that sit behind a load balancer. Unfortunately, the version hashes of the lang.js files are sometimes different from one server to the next, resulting in 404's if the page and the asset are loaded from different servers.
The reason for this is because the ordering of the encoded json of the messages is not always the same. The only solution I can think of is to recursively ksort the messages so that ordering is consistent.
Hi! I've noticed this strange behaviour with L5.1: if I use a key like 'foo' when I call Lang.has('messages.foo') I get true. But if I use a key like 'foo-bar' or 'foo_bar' the get method returns false.
Hey.
I am only gonna be using a few lang files in my project, so converting them all to JS seems like a bit of an overkill.
It'd be much nicer if I could do something like resources/lang/(All where name == x) etc.
That way I could collect all my langs for JS in a single file.
Hi
I've installed the v.1.3.0 in the Laravel 5.3, generated the lang file:
php artisan lang:js public/js/lang.js
added the file to my template:
...
<script src="{{ url('/js/lang.js') }}"></script>
<script src="{{ url('/js/webapp.js') }}"></script>
</body>
</html>
and I'm getting an error in the Chrome 52 console:
Uncaught TypeError: Lang.setMessages is not a function (lang.js:9)
This is my lang.js file:
/*!
* Lang.js for Laravel localization in JavaScript.
*
* @version 1.1.0
* @license MIT
* @site https://github.com/rmariuzzo/Lang.js
* @author Rubens Mariuzzo <[email protected]>
*/
(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define([],factory())}else if(typeof exports==="object"){module.exports=factory()}else{root.Lang=factory()}})(this,function(){"use strict";var defaults={locale:"en"};var Lang=function(options){this.locale=options.locale||defaults.locale;this.fallback=options.fallback;this.messages=options.messages};Lang.prototype.setMessages=function(messages){this.messages=messages};Lang.prototype.getLocale=function(){return this.locale||options.defaultLocale};Lang.prototype.setLocale=function(locale){this.locale=locale};Lang.prototype.getFallback=function(){return this.fallback};Lang.prototype.setFallback=function(fallback){this.fallback=fallback};Lang.prototype.has=function(key,locale){if(typeof key!=="string"||!this.messages){return false}return this._getMessage(key,locale)!==null};Lang.prototype.get=function(key,replacements,locale){if(!this.has(key)){return key}var message=this._getMessage(key,locale);if(message===null){return key}if(replacements){message=this._applyReplacements(message,replacements)}return message};Lang.prototype.trans=function(key,replacements){return this.get(key,replacements)};Lang.prototype.choice=function(key,number,replacements,locale){replacements=typeof replacements!=="undefined"?replacements:{};replacements.count=number;var message=this.get(key,replacements,locale);if(message===null||message===undefined){return message}var messageParts=message.split("|");var explicitRules=[];var regex=/{\d+}\s(.+)|\[\d+,\d+\]\s(.+)|\[\d+,Inf\]\s(.+)/;for(var i=0;i<messageParts.length;i++){messageParts[i]=messageParts[i].trim();if(regex.test(messageParts[i])){var messageSpaceSplit=messageParts[i].split(/\s/);explicitRules.push(messageSpaceSplit.shift());messageParts[i]=messageSpaceSplit.join(" ")}}if(messageParts.length===1){return message}for(var j=0;j<explicitRules.length;j++){if(this._testInterval(number,explicitRules[j])){return messageParts[j]}}var pluralForm=this._getPluralForm(number);return messageParts[pluralForm]};Lang.prototype.transChoice=function(key,count,replacements){return this.choice(key,count,replacements)};Lang.prototype._parseKey=function(key,locale){if(typeof key!=="string"||typeof locale!=="string"){return null}var segments=key.split(".");return{source:locale+"."+segments[0].replace("/","."),sourceFallback:this.getFallback()+"."+segments[0].replace("/","."),entries:segments.slice(1)}};Lang.prototype._getMessage=function(key,locale){locale=locale||this.getLocale();key=this._parseKey(key,locale);if(this.messages[key.source]===undefined&&this.messages[key.sourceFallback]===undefined){return null}var message=this.messages[key.source]||this.messages[key.sourceFallback];while(key.entries.length&&(message=message[key.entries.shift()]));if(typeof message!=="string"){return null}return message};Lang.prototype._applyReplacements=function(message,replacements){for(var replace in replacements){message=message.split(":"+replace).join(replacements[replace])}return message};Lang.prototype._testInterval=function(count,interval){return false};Lang.prototype._getPluralForm=function(count){switch(this.locale){case"az":case"bo":case"dz":case"id":case"ja":case"jv":case"ka":case"km":case"kn":case"ko":case"ms":case"th":case"tr":case"vi":case"zh":return 0;case"af":case"bn":case"bg":case"ca":case"da":case"de":case"el":case"en":case"eo":case"es":case"et":case"eu":case"fa":case"fi":case"fo":case"fur":case"fy":case"gl":case"gu":case"ha":case"he":case"hu":case"is":case"it":case"ku":case"lb":case"ml":case"mn":case"mr":case"nah":case"nb":case"ne":case"nl":case"nn":case"no":case"om":case"or":case"pa":case"pap":case"ps":case"pt":case"so":case"sq":case"sv":case"sw":case"ta":case"te":case"tk":case"ur":case"zu":return count==1?0:1;case"am":case"bh":case"fil":case"fr":case"gun":case"hi":case"hy":case"ln":case"mg":case"nso":case"xbr":case"ti":case"wa":return count==0||count==1?0:1;case"be":case"bs":case"hr":case"ru":case"sr":case"uk":return count%10==1&&count%100!=11?0:count%10>=2&&count%10<=4&&(count%100<10||count%100>=20)?1:2;case"cs":case"sk":return count==1?0:count>=2&&count<=4?1:2;case"ga":return count==1?0:count==2?1:2;case"lt":return count%10==1&&count%100!=11?0:count%10>=2&&(count%100<10||count%100>=20)?1:2;case"sl":return count%100==1?0:count%100==2?1:count%100==3||count%100==4?2:3;case"mk":return count%10==1?0:1;case"mt":return count==1?0:count==0||count%100>1&&count%100<11?1:count%100>10&&count%100<20?2:3;case"lv":return count==0?0:count%10==1&&count%100!=11?1:2;case"pl":return count==1?0:count%10>=2&&count%10<=4&&(count%100<12||count%100>14)?1:2;case"cy":return count==1?0:count==2?1:count==8||count==11?2:3;case"ro":return count==1?0:count==0||count%100>0&&count%100<20?1:2;case"ar":return count==0?0:count==1?1:count==2?2:count%100>=3&&count%100<=10?3:count%100>=11&&count%100<=99?4:5;default:return 0}};return Lang});
(function () {
Lang.setMessages({"en.validation":{"accepted":"The :attribute must be accepted.","active_url":"The :attribute is not a valid URL.","after":"The :attribute must be a date after :date.","alpha":"The :attribute may only contain letters.","alpha_dash":"The :attribute may only contain letters, numbers, and dashes.","alpha_num":"The :attribute may only contain letters and numbers.","array":"The :attribute must be an array.","before":"The :attribute must be a date before :date.","between":{"numeric":"The :attribute must be between :min and :max.","file":"The :attribute must be between :min and :max kilobytes.","string":"The :attribute must be between :min and :max characters.","array":"The :attribute must have between :min and :max items."},"boolean":"The :attribute field must be true or false.","confirmed":"The :attribute confirmation does not match.","date":"The :attribute is not a valid date.","date_format":"The :attribute does not match the format :format.","different":"The :attribute and :other must be different.","digits":"The :attribute must be :digits digits.","digits_between":"The :attribute must be between :min and :max digits.","dimensions":"The :attribute has invalid image dimensions.","distinct":"The :attribute field has a duplicate value.","email":"The :attribute must be a valid email address.","exists":"The selected :attribute is invalid.","file":"The :attribute must be a file.","filled":"The :attribute field is required.","image":"The :attribute must be an image.","in":"The selected :attribute is invalid.","in_array":"The :attribute field does not exist in :other.","integer":"The :attribute must be an integer.","ip":"The :attribute must be a valid IP address.","json":"The :attribute must be a valid JSON string.","max":{"numeric":"The :attribute may not be greater than :max.","file":"The :attribute may not be greater than :max kilobytes.","string":"The :attribute may not be greater than :max characters.","array":"The :attribute may not have more than :max items."},"mimes":"The :attribute must be a file of type: :values.","min":{"numeric":"The :attribute must be at least :min.","file":"The :attribute must be at least :min kilobytes.","string":"The :attribute must be at least :min characters.","array":"The :attribute must have at least :min items."},"not_in":"The selected :attribute is invalid.","numeric":"The :attribute must be a number.","present":"The :attribute field must be present.","regex":"The :attribute format is invalid.","required":"The :attribute field is required.","required_if":"The :attribute field is required when :other is :value.","required_unless":"The :attribute field is required unless :other is in :values.","required_with":"The :attribute field is required when :values is present.","required_with_all":"The :attribute field is required when :values is present.","required_without":"The :attribute field is required when :values is not present.","required_without_all":"The :attribute field is required when none of :values are present.","same":"The :attribute and :other must match.","size":{"numeric":"The :attribute must be :size.","file":"The :attribute must be :size kilobytes.","string":"The :attribute must be :size characters.","array":"The :attribute must contain :size items."},"string":"The :attribute must be a string.","timezone":"The :attribute must be a valid zone.","unique":"The :attribute has already been taken.","url":"The :attribute format is invalid.","custom":{"attribute-name":{"rule-name":"custom-message"}},"attributes":[]},"en.passwords":{"password":"Passwords must be at least six characters and match the confirmation.","reset":"Your password has been reset!","sent":"We have e-mailed your password reset link!","token":"This password reset token is invalid.","user":"We can't find a user with that e-mail address."},"en.auth":{"failed":"These credentials do not match our records.","throttle":"Too many login attempts. Please try again in :seconds seconds."},"en.pagination":{"previous":"« Previous","next":"Next »"}});
})();
I cannot find the reason of the console error. Do you know what it is?
Thanks for your work.
en/site.php
'views_count' => '{0} No Views|{1} :count View|[2,Inf] :count Views'
JS Console
Lang.choice('site.views_count', 0, {'count': 0})
Output: "0 View"
Lang.choice('site.views_count', 1, {'count': 1})
Output: "No Views"
Lang.choice('site.views_count', 2, {'count': 2})
Output: "2 View"
I have installed it on a laravel project. But I don’t get the artisan command to work. I always get: [Symfony\Component\Console\Exception\CommandNotFoundException]
There are no commands defined in the "lang" namespace.
In laravel I'm using Symfony localization, like this:
"{0}Items|{1}Item|[2,Inf]Items" etc
But your addon doesnt support it. Could u please add support of such things?
Hello. i have some problems when i updated package. I use laravel 4, and when i tried to generate javascript.js file, using:
php artisan lang:js
i had an error:
[Exception]
/Users/apple/Documents/project/laravel/resources/lang doesn't exists!
I am not sure, but maybe this depends on line 69 of LaravelJsLocalizationServiceProvider.php file...
Hi @rmariuzzo ,
this is great package, very usefull, i try this for my project now.
i have a problem , how to include result generate lang.js to webpack?
i try using this code but error
import Lang from 'lang.js';
require('./localize');
error message Uncaught ReferenceError: Lang is not defined
any solution for me?
thanks
If I want to have my translation files for the admin area under en/admin it does now work.
Let's say you have en/admin/blog.php
Then it seems it crashes.
Thanks!
Running "php artisan lang:js" after installation results in "There are no commands defined in the "lang" namespace." in Laravel 5.3
Sometime the language files can get very big. I usually create language files for each page. To avoid that all other language strings (from other pages) get loaded it would be cool, if I could specify via elixir by parameter which language files should be pulled, so that i can create a language js file for each page. The loading overhead can be reduced that way.
The following is defined in php and is working fine in my blade templates:
'apple_count' => '{0} :i apples |[1,1] :i apple |[2,Inf] :i apples'
@choice('apple_count', 0, ['i' => 0]) prints "0 apples"
@choice('apple_count', 1, ['i' => 1]) prints "1 apple"
@choice('apple_count', 2, ['i' => 2]) prints "2 apples"
Doing the same with JS-Localization, doesn't work as expected, it seams the JS version only supports the 'string1|string2|string3' syntax?
Lang.choice('apple_count', 0, {'i':0}); //prints "0 apples"
Lang.choice('apple_count', 1, {'i':1}); //prints "1 apples"
Lang.choice('apple_count', 2, {'i':2}); //prints "2 apple"
trying to translate a currency does not work
translating with $:count CAD
is fine if we are staying with north american currency standards and pass in values like 5.00 but this would be invalid for other places such as france which would need the translation to be return as 5,00 € (comma instead of dot)
I'm currently working with Laravel 5.4 which uses the new Laravel Mix package by default and removes support for Gulp/Elixir. In order to generate the language file automatically during asset compilation I took the following steps:
Add "webpack-shell-plugin" (I'm currently using version "0.3.5") to package.json's "devDependencies" section.
Add the following to webpack.mix.js:
const WebpackShellPlugin = require('webpack-shell-plugin');
// Add shell command plugin configured to create JavaScript language file
mix.webpackConfig({
plugins:
[
new WebpackShellPlugin({onBuildStart:['php artisan lang:js --quiet'], onBuildEnd:[]})
]
});
Hello, there are small bug in the code.
Problem is that on windows directory separator is "" instead of "/".
That means, that following code you have won't work:
\Mariuzzo\LaravelJsLocalization\Generators\LangJsGenerator::isMessagesExcluded
protected function isMessagesExcluded($filePath)
{
if (empty($this->messagesIncluded)) {
return false;
}
$localeDirSeparatorPosition = strpos($filePath, '/');
$filePath = substr($filePath, $localeDirSeparatorPosition);
$filePath = ltrim($filePath, '/');
$filePath = substr($filePath, 0, -4);
if (in_array($filePath, $this->messagesIncluded)) {
return false;
}
return true;
}
Please, fix it so it will work on windows too.
Easy fix would be to add following replace:
$filePath = str_replace(DIRECTORY_SEPARATOR,'/',$filePath);
However, I am not sure that this will be sufficient.
Please, take a look on this, I can test on windows, if needed.
Does this package support laravel 5.1? If so, can you please update the composer.json.
Thnaks.
After following the Instructions I am getting Internal server error on latest laravel 5.4
This repository host the JavaScript library used for Laravel JS Localization. If you are already using Laravel JS Localization you don't need to use this too as it comes automatically bundled.
Actually, it doesn't. Although I did npm install lang.js
, the following code doesn't work.
Uncaught ReferenceError: Lang is not defined
messages.js:108 Lang = new Lang();
import Lang from 'lang.js'
require('./messages.js')
Composer
{
"name": "mariuzzo/laravel-js-localization",
"version": "v1.3.1",
}
It's a meta issue to cover and discuss the concept of generator file registry.
Include all keys from validation.php
file. #47
'messages' => [
'validation',
],
Include all keys in forum/post.php
file. #48
'messages' => [
'forum/post',
],
Include "accepted"
key from validation.php
file.
'messages' => [
'validation.accepted',
]
Include "author"
key from forum/post.php
file.
'messages' => [
'forum/post.author',
]
Recursively include all directories, files and keys from forum
directory.
'messages' => [
'forum/*',
]
Ability to include\exclude files from command line #41
php artisan lang:js -e auth -e passwords
ReferenceError: Lang is not defined Lang = new Lang();
This points to the line in package code after the lang.min.js code
Still having this issue after update using laravel, laravel elixir webpack. Am i doing something wrong?
gulpfile looks like this
const elixir = require('laravel-elixir');
const shell = require('gulp-shell');
require('laravel-elixir-webpack-react');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
var Task = elixir.Task;
elixir.extend('langjs', function(path) {
new Task('langjs', function() {
gulp.src('').pipe(shell('php artisan lang:js ' + (path || 'resources/assets/js/translations.js')));
});
});
elixir(mix => {
mix.sass('app.scss')
.langjs()
.webpack([
'translations.js',
'app.jsx'
], 'public/js/app.js')
.version([
'css/app.css',
'js/app.js'
]);
});
Then i tryed even import Lang from translations.js in my component without having translations included in gulp file. Both cases same issue.
import Lang from '../../translations.js'
Hey team! I'm thinking on how we should manages versions within our repo. As this package is similar to Laravel, I would consider following their guide.
We would end up with the following branches:
master
— upcoming version.5.1
— Laravel 5.1 compatible version.5.0
— Laravel 5.0 compatible version.4.2
— Laravel 4.2 compatible version.Additional branches:
5.1/fix/issue-1
, 5.0/fix/another-issue
and so on.feature/superpower
, feature/simple-power
and so on.All major feature should be merged to master
(upcoming version). All minor feature should be merged to a particular version and backward compatibility to previous version.
What do you think? @vluzrmos @gpopoteur @okaufmann @xAockd
I'm building a Laravel 5 app using React JS and I would really love this to be updated, problem is I'm not too sure what is causing the conflicts, seems like the Illuminate requirements?
With Laravel Translator API, we have the ability to convert some replacements patterns letter to uppercase or lowercase.
For example, if you replace :Exclude
by passing [ exclude => "exclude me" ], you will obtain "Exclude me" (first E is capitalized as in translation pattern).
It should be useful to have it in Laravel-JS-Localization 👍
Hi,
Would you mind changing your laravel dependency to 5.1.|5.2.? It should work, the changes were not breaking.
Cheers,
Ramon
lang.js is not exist.
how can i?
Lang.prototype._parseKey = function(key) {
if (typeof key !== 'string') {
return null;
}
var segments = key.split('.');
return {
source: this.getLocale() + '.' + segments[0],
entries: segments.slice(1)
};
};
My messages are builе with backslash, and my main key(source) build incorrect.
For correct work I should replace '.' for ''
Hi!
I have successfully created the messages.js file.
Now I want to use it. However, "Lang" is not recognized.
E.g., if I take from the documentation the following (not even using messages.js):
var lang = new Lang({
messages: {
'en.greetings': {
'hi': 'Hi'
},
}
});
lang.get('greetings.hi');
// > "Hi"
.. I cannot get any output. Actually the script stops there. I guess, I have make an import or something similar.
Thanks for any help!
Hi all,
I need print variable message to template html without delay.
Can use angularjs or javascript.
Thanks,
Laravel 5.4 introduces the asterisk symbol for defining the infinity of a pluralization string (instead of «Inf») which gets ignored by Lang.js using the Artisan command to generate the lang.js file.
I have suggestion for setting locale and fallback locale in "localization-js.php" config file.
The problem is with generated .js file. Lang.setLocale() and Lang.setFallback() is not provided so I need to include it manually on all pages where I'm using Lang JS.
Is there any options to generate JS file with already set locale and fallback ?
It is said in the README that this library supports Laravel 4.2. However, your composer.json has a laravel dependency of laravel 5, preventing it to run on 4.2.
Is this package not compatible with 4.2 anymore, or is it a typo? I am truly interested in using it.
Hello.
I'm trying to get some languages texts from a subfolder.
The result message.js is creating the file correctly with the following code:
(function () {
Lang = new Lang();
Lang.setMessages({"en.javascript.datatables":{"emptyTable":"No data available in table"},"it.javascript.datatables":{"emptyTable":"Alcun dato disponibile"}});
})();
I checked over chrome console, and Lang has locale set to "it", so, I tried to do
Lang.get('javascript.datatables.emptyTable');
but it can't find nothing, in fact that string returns the pattern I wrote.
I'm executing wrongly the query for that string?
I also tried with a non subfolder file, and that worked perfectly...
Thanks
The README.md
needs to match current and upcoming changes in v1.3.0.
Add tests against Laravel 5.4
There's one char differences between the repo in GH and the package published in Packagist:
rmariuzzo/Laravel-JS-Localization # Github
•mariuzzo/Laravel-JS-Localization # Packagist
In the past this lead me to confusion when installing the package via Composer, because I didn't notice the package name is without the r
in the start.
What do you think collaborators? @gpopoteur @xAockd @okaufmann
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.