Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to internationalize string in coffeescript with i18n value?

My problem is fairly simple: I have a string in one of my coffeescripts that I need to internationalize with an i18n value in my Rails application. Here's my code:

 $ ->
      $("#order_accepted_terms").on 'invalid', ->
        this.setCustomValidity('Die AGB müssen akzeptiert werden.')

Anyone got any ideas?

like image 858
NickEckhart Avatar asked Nov 03 '14 08:11

NickEckhart


1 Answers

I usually use this gem - https://github.com/fnando/i18n-js. It behaves much like native Rails I18n. After configuring the gem (check the readme at github) you add to the end of your layout (example is in Haml)

  = javascript_tag do
    I18n.defaultLocale = "#{I18n.default_locale}"
    I18n.locale = "#{I18n.locale}"

to set default and current locales and then you can use I18n in javascript (and coffeescript) as follows (some examples from the readme):

I18n.t("some.scoped.translation")
I18n.l("time.formats.short", "2009-09-18 23:12:43")

Also passing parameters to translations is supported. Considering you have a translation

en:
  users:
    greet: "Hello %{name}!"

you can do this

I18n.t("users.greet", {name: 'Nick'})

and you'll get as a result

Hello Nick!

You'll find much more examples following the link above.

like image 116
trushkevich Avatar answered Oct 05 '22 23:10

trushkevich