admin管理员组

文章数量:1287561

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?

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?

Share Improve this question asked Nov 3, 2014 at 8:08 NickEckhartNickEckhart 4782 gold badges8 silver badges21 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8

I usually use this gem - https://github./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.

In my opinion, a better way (and one that doesn't require yet another gem, remember - performance) is to include an object with internationalized messages as a global scoped javascript variable. So you'd go about it this way (for Ruby on Rails):

1. in your application.html.erb add tags right after title (before any other javascript files are referenced)

2. add a global scope variable object within those inline script tags in head

generalMessages = {
    someMessage: '<%= t 'path.to.some_message_in_yml' %>',
    anotherMessage: '<%= t 'path.another_message' %>'
}

3. reference the variable (in javascript/coffeescript/typescript) as:

foo = generalMessages.someMessage

Voila.

A similar approach (just different syntax how to reference and print out the internationalized messages, obviously) will also work for any other language that supports internationalization and has no way to add those internationalized strings directly in javascript.

if you're looking for javascript based i18n library. You can check i18next out. It's good for me.

本文标签: javascriptHow to internationalize string in coffeescript with i18n valueStack Overflow