krepysh-spec / lang-generator
A package to have Laravel translation feature in VueJs
Requires
- php: ^8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- phpunit/phpunit: ^9.5
- psalm/plugin-laravel: ^2.0
- vimeo/psalm: ^4.24
README
Install
composer require krepysh-spec/lang-generator
In the config/app.php file add the service provider
'providers' => [ // KrepyshSpec\LangGenerator\TranslationServiceProvider::class, // ];
Publish the package assets by running the command
php artisan vendor:publish --provider="KrepyshSpec\LangGenerator\TranslationServiceProvider"
This will publish the Translation.js file in resources/js/VueTranslation directory
Run the artisan command
php artisan VueTranslation:generate --watch=1
This will compile down all the translation files in the resources/lang directory in the file resources/js/VueTranslation/translations.json
Open the file resources/js/app.js and add the Translation helper
window.Vue = require('vue'); // If you want to add to window object window.translate=require('./VueTranslation/Translation').default.translate; // If you want to use it in your vue components Vue.prototype.translate=require('./VueTranslation/Translation').default.translate;
Compile the assets by running the command
npm run development // or watch or production
How to switch the languages?
This will get the current language form the document lang attribute
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> </body> </html>
How to use?
Imagine this is the directory structure of resources/lang
|--en |--auth.php |--pagination.php |--passwords.php |--validation.php |--messages.php |--fr |--auth.php |--pagination.php |--passwords.php |--validation.php |--messages.php
And the messages.php file is something like
return [ 'foo'=>[ 'bar'=>'Some message' ] ];
You can get the value by calling the translate method
translate('messages.foo.bar')
Example in Vue component
<template> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Example Component</div> <div class="card-body"> {{translate('messages.foo.bar')}} </div> </div> </div> </div> </div> </template> <script> export default { } </script>
Uses Fallback Locale
To interact same like Laravel trans() insert in your layout
<meta name="fallback_locale" content="{{ config('app.fallback_locale') }}">
Replace attributes
It's not recommended to use this package for showing validation errors but if you want you can replace :attribute, :size etc by passing the second argument as an object.
translate('validation.required',{ attribute:translate('validation.attributes.title') });
Notice: if it could not find the value for the key you passed it will return the exact key
Support
For support, email evgeniymykhalichenko@gmail.com or telegram @krep1sh
License
MIT