0

I am using 'handlebars_assets' and i18n-js in my Rails app, I have a handlebar template, where I want to translate rails model object attributes.

app/assets/javascripts/templates/questions.show.hbs

<div class="question-body">
      <div><strong>{{tAttr 'body'}}:</strong> {{question.body}}</div>
      {{#if question.race}}
        <div><strong>{{tAttr 'which_race'}}:</strong> {{question.which_race}}</div>
      {{/if}}
      <div><strong>{{tAttr 'half_breed'}}:</strong> {{question.half_breed}}</div>
      <div><strong>{{tAttr 'age'}}:</strong> {{question.age}}</div>
      <div><strong>{{tAttr 'weight'}}:</strong> {{question.weight}}</div>
      <div><strong>{{tAttr 'gender'}}:</strong> {{question.gender}}</div>
</div>  

I have a simple form which I submit asynchronousyly with remote: true and if the record is created I append the template above to the DOM. This is my JS part where I handle the AJAX response.

Handlebars.registerHelper('tAttr',
      function(str){
        return (I18n != undefined ? I18n.t('activerecord.attributes.question.' + str) : str);
      }
    );

$('#question-form').on('ajax:success', function (evt, question, status, xhr) {
    var $form = $(evt.currentTarget);
    var questionHTML = HandlebarsTemplates['questions/show']({
      question: question,
      idx: Date.now(),
      authToken: $('meta[name="csrf-token"]').attr('content')
    });
    $('#questions').prepend(questionHTML);

    $form.find('input[type=text], textarea').val('');
    $form.find('.form-errors').html('');
  });

Here I should have German names but I get English names. I have confirmed that the I18n.locale is :de on the server side but I am getting English names of attributes. I have tried exporting the translations manually by rake i18n:js:export but that didn't help. How can I fix it?

Community
  • 1
  • 1
jedi
  • 2,003
  • 5
  • 28
  • 66

1 Answers1

0

I've managed to fix this. I have learned to debug javascript in DevTools and was able to notice that I18n.defaultLocale was set to "en". I have fixed it by adding this snippet in my rails view.

<script>
  I18n.locale = "de"
</script>
jedi
  • 2,003
  • 5
  • 28
  • 66