Coder Social home page Coder Social logo

rmariuzzo / laravel-js-localization Goto Github PK

View Code? Open in Web Editor NEW
581.0 20.0 168.0 359 KB

🌐 Convert your Laravel messages and consume them in the front-end!

Home Page: https://github.com/rmariuzzo/laravel-js-localization

License: MIT License

PHP 98.75% JavaScript 0.47% Shell 0.78%
php javascript localization i18n l10n internationalization laravel laravel-package laravel-5-package laravel-4-package

laravel-js-localization's Introduction

Laravel JS Localization - Convert you Laravel messages and use them in the front-end!

Laravel 5.5 Laravel 4.2 Latest Stable Version Total Downloads License

This package convert all your localization messages from your Laravel app to JavaScript with a small library to interact with those messages following a very similar syntax you are familiar with.

Features

  • Support Laravel 4.2, 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 6.x, 7.x and 8.x!
  • Includes Lang.js (a thin library highly inspired on Laravel's Translator class).
  • Allow to specify desired lang files to be converted to JS.
  • Lang.js API is based on Laravel's Translator class. No need to learn a whole API.

Webpack user? Try the new and shiny Laravel localization loader for Webpack!

Installation

composer require mariuzzo/laravel-js-localization

In your Laravel app go to config/app.php and add the following service provider:

Mariuzzo\LaravelJsLocalization\LaravelJsLocalizationServiceProvider::class

Usage

The Laravel-JS-Localization package provides a command that generate the JavaScript version of all your messages found at: app/lang (Laravel 4) or resources/lang (Laravel 5) directory. The resulting JavaScript file will contain all your messages plus Lang.js (a thin library highly inspired on Laravel's Translator class).

Generating JS messages

php artisan lang:js

Specifying a custom target

php artisan lang:js public/assets/dist/lang.dist.js

Compressing the JS file

php artisan lang:js -c

Specifying a custom source folder

php artisan lang:js public/assets/dist/lang.dist.js -s themes/default/lang

Output a JSON file instead.

php artisan lang:js --json

Configuration

First, publish the default package's configuration file running:

php artisan vendor:publish --provider="Mariuzzo\LaravelJsLocalization\LaravelJsLocalizationServiceProvider"

The configuration will be published to config/localization-js.php.

You may edit this file to define the messages you need in your Javascript code. Just edit the messages array in the config file. Empty messages array will include all the language files in build.

To make only pagination.php and validation.php files to be included in build process:

<?php

return [
    'messages' => [
        'pagination',
        'validation',
    ],
];

Using gulp (optional)

Install gulp-shell and then run it directly in your gulpfile.js:

var shell = require('gulp-shell');

gulp.task('langjs', shell.task('php artisan lang:js -c public/js/messages.js'));

Using Laravel's elixir (optional)

Before Elixir 4.0:

elixir.extend('langjs', function(path) {
    gulp.task('langjs', function() {
        gulp.src('').pipe(shell('php artisan lang:js ' + (path || 'public/js/messages.js')));
    });

    return this.queueTask('langjs');
});

Elixir 4.0+:

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

And use it like this:

elixir(function(mix) {
    mix.langjs();
});

Using Laravel's Mix with Laravel 5.4+ (optional)

Add "webpack-shell-plugin-next" to package.json's "devDependencies" section.

Add the following to webpack.mix.js:

const WebpackShellPluginNext = require('webpack-shell-plugin-next');

// Add shell command plugin configured to create JavaScript language file
mix.webpackConfig({
    plugins:
    [
        new WebpackShellPluginNext({onBuildStart:['php artisan lang:js --quiet'], onBuildEnd:[]})
    ]
});

Documentation

This is a quick documentation regarding Lang.js (the thin JavaScript library included by Laravel-JS-Localization). The Lang.js (a thin library highly inspired on Laravel's Translator class).

💁 Go to Lang.js documentation to see all available methods.

Getting a message

Lang.get('messages.home');

Getting a message with replacements

Lang.get('messages.welcome', { name: 'Joe' });

Changing the locale

Lang.setLocale('es');

Checking if a message key exists

Lang.has('messages.foo');

Support for singular and plural message based on a count

Lang.choice('messages.apples', 10);

Calling the choice method with replacements

Lang.choice('messages.apples', 10, { name: 'Joe' });

💁 Go to Lang.js documentation to see all available methods.

Want to contribute?

  1. Fork this repository and clone it.
  2. Create a feature branch from develop: git checkout develop; git checkout -b feature-foo.
  3. Push your commits and create a pull request.

Prerequisites:

You will need to have installed the following softwares.

  • Composer.
  • PHP 5.5+.

Development setup

After getting all the required softwares you may run the following commands to get everything ready:

  1. Install PHP dependencies:

    composer install
  2. Install test dependencies:

    composer test-install

Now you are good to go! Happy coding!

Testing

This project uses PHPUnit. All tests are stored at tests directory. To run all tests type in your terminal:

composer test

Made with ❤️ by Rubens Mariuzzo.

MIT license

laravel-js-localization's People

Contributors

ahoiroman avatar aimakun avatar antonkomarev avatar ardanirohman avatar badconker avatar cams5792 avatar datalink-wouter avatar dbpolito avatar dieg0v avatar emilmoe avatar evilangelmd avatar exfriend avatar gitter-badger avatar gpopoteur avatar grzesw avatar guilhermecfviana avatar jeremy-smith-maco avatar jjdrake avatar koost89 avatar okaufmann avatar pascalbaljet avatar rmariuzzo avatar rtheunissen avatar shawnhooper avatar spyric avatar vluzrmos avatar wilpat avatar xaockd avatar zakay avatar zgabievi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-js-localization's Issues

Tip/Idea: Use gulp to automate localization

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?

getting 500 error

After following the Instructions I am getting Internal server error on latest laravel 5.4

Support: Node modules (import/require) for generated file with bundled JS lib

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'

Ability to make replacements with uppercase/lowercase patterns

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 👍

Can't get subfolder messages

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

artisan command not working

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.

It does not work for files under folder

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!

Message keys of generated file is not consistent

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.

Feature: Optionally include JS library within generated 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

Messages are built with backslash instead of dot

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 ''

[Idea]Select which lang files to target

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.

Using default keyed translations

It appears that translations in a resources/lang/en.json file (used for translations keyed by the default text) are ignored by the generator.

Feature: add default and fallback locale in config 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 ?

Key messages with '-' or '_' chars

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.

Lang is not defined

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",
}

Problems for laravel 4

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...

Update documentation

The README.md needs to match current and upcoming changes in v1.3.0.

  • We should definitively remove the Lang.js documentation and instead refer to it with a link.

Uncaught TypeError: Lang.setMessages is not a function

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":"&laquo; Previous","next":"Next &raquo;"}});
})();

I cannot find the reason of the console error. Do you know what it is?

Thanks for your work.

Development Workflow: branches

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:

  • Bug fixes — 5.1/fix/issue-1, 5.0/fix/another-issue and so on.
  • Features — 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

Can't translate with currency formatting included

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)

Lang.choice not working correctly

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"

Does not work on windows

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.

Exclude\Include files and translation keys

It's a meta issue to cover and discuss the concept of generator file registry.

Implemented

Include all keys from validation.php file. #47

'messages' => [
    'validation',
],

Include all keys in forum/post.php file. #48

'messages' => [
    'forum/post',
],

Not implemented

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

Consider updating README with Laravel 5.4 lang file generation steps

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:

  1. Add "webpack-shell-plugin" (I'm currently using version "0.3.5") to package.json's "devDependencies" section.

  2. 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:[]})
	]
});

Support Laravel 5.2

Hi,

Would you mind changing your laravel dependency to 5.1.|5.2.? It should work, the changes were not breaking.

Cheers,
Ramon

Initialization Explanation

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!

Can't get it to work! :(

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?

Support Laravel 4.2

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.

Using 'Lang' class with Vue.js

It so happens that I can't import the 'Lang' class in my Vue component; I receive a ReferenceError. Any help would be appreciated.

Feature: Default location of generated JS file

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

Move package to "rmariuzzo" instead of "mariuzzo".

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

Separate JS library from Laravel Package

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:

  • rmariuzzo/laravel-js-localization — The Laravel package.
  • rmariuzzo/lang-js — The JS lang library.

What do you think collaborators? @gpopoteur @xAockd @okaufmann

RU localization and Symfony localization

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?

Advanced Pluralization issue

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"

Laravel 5.1

Does this package support laravel 5.1? If so, can you please update the composer.json.

Thnaks.

Feature: Ability to specify path in configuration file

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.

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.