A
A
aaltw2021-12-17 14:08:26
JavaScript
aaltw, 2021-12-17 14:08:26

Localizing a .js file with RoR code?

There is a regular .js file, I need localized text in it. I came up with the following:

app.js

import { locale } from './locale.js.erb';

const locale = locale( );
translated_word = locale.translated_word;

locale.js.erb
function locale() {
  return {
    translated_word: "<%= t('words.translated_word') %>"
  }
}

export { locale }

Translations as they should be defined in ru.yml, en.yml, etc. Those. i wanted to use normal rail translation by passing it to .js. However, this didn't work, and instead of translating words, I just get text like:
{ translated_word: "<%= t('words.translated_word') %>" }

Those. rail code failed. Why?

Or maybe there is a better way to do it? Provided that the file should remain .js and not be turned into .js.erb.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oh_shi, 2021-12-19
@altw

It cannot work like that. JS is compiled once during deployment, t(...) is calculated per request. Either everything related to localization should be duplicated in js code, or translations should be pulled through ajax. You can also pervert and convert yml to json at the build stage, forward them to routes and pull up the entire set of translations depending on the locale.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question