如何在 I18n.translate 中传递参数

How to pass arguments in I18n.translate

I18n.translate 可以这样翻译 error.messages:

I18n.translate('error.messages.taken')
-> has already been taken

但是有些错误消息包含如下参数:

I18n.translate('error.messages.greater_than_or_equal_to')
-> must be greater than or equal to %{count}"

是否可以在 I18n.translate 中传递参数“count”?

key后面可以传params

I18n.translate('error.messages.greater_than_or_equal_to', count: 2)

这将允许您添加任意数量的参数

I18n.translate('error.messages.greater_than_or_equal_to {arg1}').replace('{arg1}', count)

对于多个参数,它可以是:

I18n.translate('error.messages.greater_than_or_equal_to', {
  count: 2,
  foo: 'bar'
})

如果你有

"greeting": "hi {name}"

你需要写

i18n.translate('greeting', {values: {name: 'John'}});

如果需要传递散列(动态)参数,可以使用双 splat 运算符 **

values = { count: 2, name: 'John' }
I18n.t('error.messages.greater_than_or_equal_to', **values)

在 ROR 中,我能够使用

传递多个参数

#app/mailers/sample_mailer.rb

(to: email, subject: t('<mailer_scope>.<action_name>.subject', <locale_variable_name_1>: <Rails_variable_name_1>, <locale_variable_name_2>: <Rails_variable_name_2>))

#config/locales/en.yml

mailer_scope:
    action_name:
      `subject: "Insert e-mail subject here: %{locale_variable_name_1} - %{locale_variable_name_2}"

您可以从 Rails 指南中阅读此官方 docs