'Laravel's localization on JavaScript Variables
I have some JavaScript variables that I output on a rating scale as shown below.
I now want to achieve Laravel's localization therefore translate the variables before outputting them on the browser.
How can I achieve this? I tried as below but it does not get converted.
var ratingScale = {1: 'Terrible, 2: 'Poor', 3: 'Average', 4: 'Good', 5: 'Excellent'};
I would want to Localize the variables Terrible
, Poor
, Average
, Good
, and Excellent
.
I tried this
var one = "<?php echo trans('form.one'); ?>";
var ratingScale = {1: one, 2: 'Poor', 3: 'Average', 4: 'Good', 5: 'Excellent'};
But on the browser this is outputted <?php echo trans('form.one'); ?>
Anyone lead me here?
Solution 1:[1]
You are creating a litteral string containing that. What you probably Would like to do is output the translations as json or data-attributes somewhere in the DOM. Then pick up these variables with JavaScript.
JSON in DOM
In your blade output json_encoded the translations, inside script tags.
e.g. example.blade.php
<script>
var ratingScale = {!! $ratingScale !!}
</script>
data attribute
output the strings as data attributes in some html element
e.g. example.blade.php
<form data-scale1="{{ratingScale[1]}}">
etc.
call via xhr / ajax to the server
axios.get('/ratingScales');
Create an extra endpoint to retrieve these translations as json.
Solution 2:[2]
Try this below code it will work if you are in blade file.(you can move you js code in blade file and try this also it will work)
var one = {{ trans('form.one') }};
Solution 3:[3]
What I do is to include such javascript file in my blade templates like always:
@extends('adminlte::layouts.app')
@section('htmlheader_title')
Viajes en curso
@stop
@section('links')
@include('zendesk.widget')
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="{{ asset('/css/app_adminlte_custom.css') }}"/>
<script type="text/javascript" src="{{ asset('/js/bower_components/jquery/dist/jquery.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('/js/sweetalert.min.js') }}"></script>
<script type="text/javascript" src="{!! asset('js/app/trips.js') !!}"></script>
@stop
@section('notifications_menu')
@include('app.partials.notifications_menu')
@stop
........ big etc ....
But, at some point I initialize the variables I need from this blade file itself:
@section('extra-js')
<script type="text/javascript">
var myTranslatedTitle = {{ trans('whatever') }};
var numAcceptedTrips = {{ $numAcceptedTrips }};
</script>
@yield('extra-js')
Just bear in mind these variables are global.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jigar |
Solution 3 | javier_domenech |