Have you ever wanted to use the same Laravel translations you use on the back-end in your front-end code?
Laravel Translations Loader is a webpack loader that enables you to load your Laravel translations into your javascript bundle.
Instead of doing HTTP requests to fetch translations, the package enters in the middle of the asset compilation process and translates your PHP translation files (JSON and PHP) into a JSON object so you can use however you like.
It works out of the box with packages like vue-i18n or with a few configuration tweaks with the popular i18next package.
Show me the code
The first step, is to install the package using NPM or Yarn.
1npm install @kirschbaum-development/laravel-translations-loader --save2yarn add @kirschbaum-development/laravel-translations-loader --save
Or, by using Yarn.
1npm install @kirschbaum-development/laravel-translations-loader --save
Basically, in your javascript file, you just need to include the following line to import your language bundle.
1import languageBundle from2'@kirschbaum-development/laravel-translations-loader!@kirschbaum-development/laravel-translations-loader';
This will load and parse all your language files, including PHP and JSON translations. The languageBundle
will look something like this:
1{ 2 "en": { 3 "auth": { 4 "failed": "These credentials do not match our records." 5 } 6 }, 7 "es": { 8 "auth": { 9 "failed": "Estas credenciales no coinciden con nuestros registros."10 }11 }12}
Along with all other translations you may have on your translations folder.
There are options for loading either just PHP or JSON translations files, as well as adding a namespace between the lang keys and the actual translations that some packages require. You can check the different loading options on the readme of the project. And please fill out an issue if you have any troubles or suggestions.
Example using vue–i18n
Notice you can directly pass the languageBundle
object as a parameter into the VueI18n
constructor.
1import languageBundle from '@kirschbaum-development/laravel-translations-loader!@kirschbaum-development/laravel-translations-loader';2import VueI18n from 'vue-i18n';3Vue.use(VueI18n);4const i18n = new VueI18n({5 locale: window.Locale,6 messages: languageBundle,7})
And on any vue component, you can just use the $t
function, like the following example:
1<template>2 <span>{{ $t('auth.failed') }}</span>3 <!-- this will output the same as {{ trans('auth.failed') }} using Laravel -->4</template>
0 comments:
Post a Comment
Thanks