Leo
Leo

Reputation: 583

How to pass arguments in I18n.translate

I18n.translate can translate error.messages like this:

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

But there are some error messages that contains arguments like:

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

Is it possible to pass the argument ‘count’ in the I18n.translate?

Upvotes: 19

Views: 40893

Answers (6)

Lea Tinoso
Lea Tinoso

Reputation: 2343

In ROR I was able to pass multiple arguments using

#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}"

You may read this official docs from Rails guides.

Upvotes: 0

Datt
Datt

Reputation: 881

If you need to pass a hash(dynamic) argument, you can use the double splat operator **.

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

Upvotes: 6

nix86
nix86

Reputation: 3037

If you have

"greeting": "hi {name}"

You need to write

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

Upvotes: 1

user3773080
user3773080

Reputation: 63

For multiple params it could be:

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

Upvotes: 6

Vijay
Vijay

Reputation: 1092

This would allow you to add as many arguments as you want

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

Upvotes: 2

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

You can pass the params after the key

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

Upvotes: 30

Related Questions