Inside tag in my index.html.eex i can use this syntax to retrive text.
<%= gettext "Login failed!"%>
Now i have a js file used for validating fields, and i load this file as a script inside index.html.eex.
Everything works fine but i need to use gettext for Phoenix text translation inside the js file. I know that <%= %> syntax won't compile outside .eex files, however i refuse to put all my validation logic code inside a in index.html.eex What can i do to get phoenix code inside a js file?
You can store the translations in a variable in index.html.eex
and then access it from the JS files. Here's an example:
Add this to the top of index.html.eex
:
<script>
var Translations = {
"login_failed": <%= raw Poison.encode!(gettext("Login failed!")) %>,
};
</script>
Now in your JS file, do:
console.log(Translations.login_failed)
A better way would be to create a list of such translations and inject them in your layout file:
<script>
var Translations = {
"login_failed": <%= raw Poison.encode!(gettext("Login failed!")) %>,
"some_other_error": <%= raw Poison.encode!(gettext("Some other error!")) %>,
};
</script>
This way all translations will be available in app.js
.
Why raw
and Poison.encode!
?
Simply doing "<%= thing %>"
or '<%= thing %>'
will break if thing
contains quotes or newlines (and probably some other special characters). Poison.encode!
will convert the value into valid JSON (which is also valid JS) and raw
will ensure this value is not double escaped.