1

I'm having problems with the encoding of some localized strings in laravel.

In my localization file for Spanish I have (among many other strings):

"truck" => "camión"

In myView.blade.php, if I print the string directly:

<h2>{{trans('localizationFile.truck'}}</h2>

It works fine and prints

camión

But if I try to use that same string in javascript:

<script>
$(document).ready(function()
{           
    alert("{{trans('events.camion')}}");
}
</script>

It codifies the accented o and the alert reads: cami&oacute;n

How can I fix that? Or am I doing something wrong? Perhaps that's not the way to localize javascript messages...

Thanks in advance!

1 Answer 1

1

When outputting an alert, the HTML entities are not decoded so they are show as plain text. The simplest solution to fix this is to add the text to an HTML element and return its content via the text method, which will decode the HTML entities:

<script>
    $(document).ready(function () {
        alert($('<div>{{trans('events.camion')}}</div>').text());
    }
</script>

The above uses jQuery's html method, but this can be achieved with vanilla JS and innerHtml.


If you want to include an extra JS library you can use he, that takes care of decoding. So it would look something like this:

<script>
    $(document).ready(function () {
        alert(he.decode({{trans('events.camion')}}));
    }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Hum.. I thought about "saving" the text in html entities but looked too complicated. I think I'll go with the library, looks much cleaner. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.