kg-bot / laravel-localization-to-vue Goto Github PK
View Code? Open in Web Editor NEWMake Laravel standard localization files available in format required by various JavaSript localization packages
License: MIT License
Make Laravel standard localization files available in format required by various JavaSript localization packages
License: MIT License
Not sure if this is a bug or if intended feature, but the regex setting (available in the laravel-localization.php config file) to exclude certain files is not applied when requesting the JSON over HTTP routes.
I have the following regex:
'file_regexp' => [
'php' => '/^((?!careers|mail_|about).)+\.php$/i',
'json' => '/^.+\.json$/i',
],
The corresponding strings are excluded when I export the language files with the command line, but when I visit the route over HTTP the exclusion was not used. Did I miss anything?
Hello,
I have followed the instructions on setting up this package with laravel. I also installed Lang.js accordingly.
From my vue component, when I call the trans.get
function in the template like this:
<p>{{ trans.get('words.share_post') }}</p>
it works fine but when I try calling trans.get
in any of my component's methods I get the error below
app.js:4145 Uncaught ReferenceError: trans is not defined
at VueComponent.onLinkCopied (app.js:4145)
at app.js:81325
at v.emit (app.js:51870)
at c.value (app.js:51870)
at c.value (app.js:51870)
at c.value (app.js:51870)
at c.value (app.js:51870)
at new c (app.js:51870)
at value (app.js:51870)
at HTMLButtonElement.<anonymous> (app.js:51870)
Please how can I resolve this.
Thanks in advance
First a question...
on your code example you're using trans.get()
function to use with the __JSON__
key, does this key work elsewhere? like Vue-i18n
? I guess not, right?
I do suggest that on the documentation we could also add a note saying this feature only works with Lang.js
The package tries to connect to Redis (or any other cache store) during the composer install
command, specifically when the @php artisan package:discover
runs.
That's a problem because when I'm building the app's Docker image, the cache store (in my case Redis) is not available yet.
Steps to reproduce the behavior:
.env
to work with Rediscomposer require kg-bot/laravel-localization-to-vue
), try to publish the config, apply the basic usage steps, and then run composer install
again, but make sure the Redis server is not available.Hello, i'm using your package together with https://kazupon.github.io/vue-i18n/
Here is the thing:
Laravel translation parameters look like ":parameter"
Vuei18n expects "{parameter}"
This is my solution:
Route::get('/lang/localization.js', function () { $translate = ExportLocalization::export()->toArray(); array_walk_recursive($translate, function (&$v, $k) { $v = preg_replace('/:(\w+)/', '{$1}', $v); }); return response()->json($translate); });
(applied a regex replace on every translated string)
It would be nice to have a built-in callback setting to customize the output
I am getting an error:
Unable to prepare route [js/localization.js] for serialization. Uses Closure.
It's because you're using a Closure
in the routes
file: https://github.com/kg-bot/laravel-localization-to-vue/blob/master/src/routes.php
Instead you should do something like:
Route::get(config('laravel-localization.routes.prefix'), 'KgBot\LaravelLocalization\Facades\ExportLocalizations@exportToArray') ...
Then in Facades\ExportLocalizations.php
add:
public static function exportToArray(){
$strings = ExportLocalizations::export()->toArray();
return response()->json($strings);
}
I have did every thing as the documentation say,
when I log the lang object I get the data exported but when I use trans.get() or trans,has() always false.
Please help me
Is your feature request related to a problem? Please describe.
The current version of this package doesn't support laravel 9
Please add support for Laravel 8 and 9.
this feature would be great to have since it would allow users to have more options on what they would be able to do with the export... it also supports i18n-ally
which is a vscode Extension
something like this would be a good format when exporting to json
php artisan export:messages --json
to those who stumble upon this Issue... here's how I generate json
files
Artisan::command('lang-export:messages-json', function () {
$languages = ExportLocalizations::export()->toArray();
foreach ($languages as $language_key => $translations) {
foreach ($translations as $translation_key => $translate) {
// dd($translation_key, $translate);
$filepath = config('laravel-localization.js.filepath', resource_path('assets/js'));
$filepath = "$filepath/$language_key";
$filename = "$translation_key.json";
$adapter = new Local($filepath);
$filesystem = new Filesystem($adapter);
$contents = json_encode($translate, JSON_PRETTY_PRINT);
if ($filesystem->has($filename)) {
$filesystem->delete($filename);
$filesystem->write($filename, $contents);
} else {
$filesystem->write($filename, $contents);
}
}
}
$this->info('Messages exported to JSON files, you can find them at '.$filepath);
return 0;
})->purpose('Export the languages to json');
if you have a directory structure like the one below,
en/passwords.php
en/auth.php
en/pagination.php
en/validation.php
ja/passwords.php
ja/auth.php
ja/pagination.php
ja/validation.php
this code will generate this output
en/passwords.json
en/auth.json
en/pagination.json
en/validation.json
ja/passwords.json
ja/auth.json
ja/pagination.json
ja/validation.json
Originally posted by @yob-yob in #70 (comment)
H I install this library, and the manually install lang.js using NPM. Messages is loaded using View Composer.
Blade
<!-- laravel-localization-to-vue JS -->
<script>
window.default_locale = "{{ config('app.lang') }}";
window.fallback_locale = "{{ config('app.fallback_locale') }}";
window.messages = @json($messages);
</script>
Then I put this in my Laravel app.js
import Lang from 'lang.js';
const default_locale = window.default_locale;
const fallback_locale = window.fallback_locale;
const messages = window.messages;
Vue.prototype.trans = new Lang( { messages, locale: default_locale, fallback: fallback_locale } );
And try to console.log in my Vue component
<script>
export default {
mounted() {
console.log(trans.get('auth.failed'));
},
}
</script>
However I get this error
[Vue warn]: Error in mounted hook: "ReferenceError: trans is not defined"
If I try this
<script>
export default {
mounted() {
console.log(this.trans.get('auth.failed'));
},
}
</script>
Will output the lang key, but not the actual value
Quick check on html, the language was loaded
This package is using the list config('laravel-localization.paths.lang_dirs')
to decide which language files must be read and parsed.
Is the a reason behind this approach ??
In my opinion there's a better way, using the list of files that Laravel-Translation has already loaded (including those files loaded via service providers of packages).
Advantages of my suggested way :
$this->loadTranslationsFrom(..);
in service providersThe reason why I submit this Feature Request before any PR, is that I'm not sure if there was any other idea behind the current approach.
By the way, I have a commit ready for it, if such change is useful, tell me to submit a PR for it.
@kg-bot 🙏🏻
You've added a constructor to:
KgBot\LaravelLocalization\Classes\ ExportLocalizations
The constructor:
public function __construct($phpRegex, $jsonRegex)
{
$this->phpRegex = $phpRegex;
$this->jsonRegex = $jsonRegex;
}
Is new and has non-typed and non-nullable arguments that cause errors. In my local version, I have overridden this class to allow for something that I need in the codebase. I did this with v1.6.1
and upon running composer update
it all breaks because the regexes have vanished, the constructor has appeared and the container cannot find the 'dependencies'.
Are you not following semantic versioning?
I'm working with Laravel Modules, and have multiple path lang https://nwidart.com/laravel-modules/
Since Laravel 6 nothing that could brake package has changed, so it's just about adding |^7 the version in composer.json.
I tried to use the Lang.js module like u showed in the example, but i am bit confused about JSON format and getting the translation by key.
Exported format:
{
'en':{
'greetings': {
'hi': 'Test'
}
},
'it': {
'greetings': {
'hi': 'Salve'
}
}
}
Lang.js required format:
{
'en.greetings': {
'hi': 'Hi',
'hello': 'Hello'
},
'it.greetings': {
'hi': 'Salve'
}
}
Vue part
// With first format
trans.get('greetings.hi'); // > "greetings.hi"
// With second format
trans.get('greetings.hi'); // > "Hi"
I have a es.json
file in the lang root directory as per Laravel documentation. I chose this option since I have a lot of translation strings.
But the export function (including artisan command) only parses .php
files. Any ideas on how to get the translations in the .json
files included?
Hi, will there be Laravel 10 support in the near future?
'php artisan export:messages 'the command first use ,it work ;
And then i change the 'lang/en' file,
use the command twice immediately ,the translate file doesnot update
Hi how to integrate this package with Spatie Laravel Translation Loader? https://github.com/spatie/laravel-translation-loader
Spatie package allow me to store language key in database, by overriding the Service Provider
Thanks
I am using vue-multiselect component and to translate their placeholders and labels globally, I am extending the component but in props, I cannot use trans.get. Error - trans is not defined. Do I need to import something here? In page components, I could use trans inside </template section. Not sure about props though
import Multiselect from 'vue-multiselect';
export default {
extends: Multiselect,
props: {
selectLabel: {
type: String,
default: trans.get('__JSON__.Press enter to select')
},
selectedLabel: {
type: String,
default: trans.get('__JSON__.Selected')
},
deselectLabel: {
type: String,
default: trans.get('__JSON__.Press enter to remove')
},
placeholder: {
type: String,
default: trans.get('__JSON__.Select option')
}
}
}
Readme file says default route is lang.js but in fact it is localization.js.
In v1.5.5 there is a problem reading default resources/lang folder.
To fix this I needed to change laravel-localization.php on line 92
from : ['resources/lang'],
to : [resource_path('lang')],
As this returns relative path and first one couldn't find lang folder.
Please fix that
Hey there, love this library for my Vue frontend, but I'm having trouble finding a way to use translation strings in my vuex store.
Is there any way to get that to work?
Thanks!
Describe the bug
When I try installing this package using the command
composer require kg-bot/laravel-localization-to-vue
, I get the error message shown below
ErrorException
Invalid argument supplied for foreach()
at vendor/kg-bot/laravel-localization-to-vue/src/Classes/ExportLocalizations.php:67
63|
64| return $this;
65| }
66|
67| foreach (config('laravel-localization.paths.lang_dirs') as $dir) {
68| try {
69|
70| // Collect language files and build array with translations
71| $files = $this->findLanguageFiles($dir);
4 [internal]:0
KgBot\LaravelLocalization\Console\Commands\ExportMessages::__construct()
I am using laravel 7 and php 7.3,
Hi, I have been using this package for while a now, every time I update the language JSON file in resources\lang
, the function trans.get(__JSON__.title)
for example, does not outputs the string from the messages file in resources\assets\js
, even if it's exported right, still won't show. However, in the first time when included this package is worked just great and just after exporting, it sometimes shows the locale string and sometimes it not. I have tried to php artisan config:cache
after every php artisan export:messages
and also didn't fix the problem. I hope there is a solution for this error.
I get this message when trying to publish config file.
Describe the bug
When i try to access the link: http://localhost/js/localization.js
this error is thrown. Malformed UTF-8 characters, possibly incorrectly encoded
To Reproduce
Steps to reproduce the behavior:
Expected behavior
Should return at least a javascript file with all the translations
Desktop (please complete the following information):
Additional context
Im using laravel 9.13.0
for new laravel version in docs
// Inside blade view
<script>
window.default_locale = "{{ config('app.lang') }}";
window.fallback_locale = "{{ config('app.fallback_locale') }}";
window.messages = @json($messages);
</script>
Should change
window.default_locale = "{{ config('app.locale') }}";
Hi
I'm struggling to import the module exported via the artisan command.
The resulting file is something like
export default messages = {"en":{"auth":{"failed":"...
When I'm trying to use it
import messages from './ll_messages';
console.log(messages);
Uncaught ReferenceError: messages is not defined
at eval (ll_messages.js?f4b1:1)
If I simplify the exported JS as
export default {"en":{"auth":{"failed":"These credent...
Then I can use the imported data.
I'm I misunderstood something here? Can you help me out please, how am I supposed to use this?
Hi,
Great package!
I hope it is not a feature request, cause hope I just don't know how to do that with your package :)
So is it possible to generate laravel translations string:
Confirm delete :name :type?
,
To:
Confirm delete {name} {type}?
,
If not, than it is feature request :)
Would it be possible do not expose the localization route by default? http://localhost/js/lang.js
Hello,
I think there is an error. Your code forms all language files as a json string. With locale attribute and translate files and values.
The lang.js needs the data as a json object as well but locale is part of the attribute e.g. "en.greetings"
var lang = new Lang({ messages: { 'en.greetings': { 'hi': 'Hi', 'hello': 'Hello' }, 'it.greetings': { 'hi': 'Salve' } } });
Can you please create a new release with the Laravel 10 support in it?
I have tried to install this package on Laravel 5.5 but i get following error
Could not find package kg-bot/laravel-localization-to-vue at any version matching your PHP version 7.0.32.0
It would be nice when u support Laravel 5.5 and PHP 7.0.
Or is there any reason why PHP 7.1 is required ?
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.