I want to add text with javascript or jquery and translate it automatically.
I tried for example:
let x = 'Cats';
$('#divToAppend').text(`{{ __('${x}') }}`)
When I do that, the text appends without translation.
{{ __('Cats') }}
in the blade file, the translation works.
Can somebody help me? I tried with the {!! __('${x}') !!}, tried with only javascript and no jQUery, but nothings changes...
Thanks!
Blade is a template engine and {{ ... }} statements are templates. When the site is loaded those templates will be evaluated on the server side to generate plain HTML which then is sent to the client. When you try to add templates using JavaScript on the client side it won't work because the server can't evaluate them.
If you want to add a translated string inside your JavaScript you have to either store all the translations in the JavaScript itself and pick the required one or send a request to the server which you let return the translated string.
You can read more about what templating is here.