06/06
2017
Use Laravel translations in javascript
Use Laravel translations in javascript, (*2)
Other languages: - Russian, (*3)
Install package:, (*4)
$ composer require misterpaladin/jstrans
Add JSTransServiceProvider
to your config/app.php
:, (*5)
<?php // ... 'providers' => [ MisterPaladin\JSTrans\JSTransServiceProvider::class, ],
Publish config:, (*6)
$ php artisan vendor:publish --tag=jstrans
Edit config/jstrans.php
, add translations you wish to use in javascript:, (*7)
return [ 'validation', ];
Include this script in your views before your javascript files:, (*8)
<script src="/vendor/misterpaladin/jstrans/js/jstrans.js" type="text/javascript"></script>
And use it in your javascript like Laravel's trans()
function:, (*9)
jstrans('validation'); // Will return whole 'validation.php' array jstrans('validation.accepted'); // Will return 'The :attribute must be accepted.' jstrans('validation.foo.bar'); // Will return 'validation.foo.bar' jstrans('validation.accepted', {attribute: 'Test'}); // Will return 'The Test must be accepted.'
You may specify additional values to overwrite localization files:, (*10)
@jstrans([ 'validation' => 'new value', ]) @jstrans([ 'foo' => trans('bar'), 'fooo' => 'baaar', ])
var validation = jstrans('validation'); // Will return 'new value', instead of 'validation.php' array