novac
novac

Reputation: 156

I18n interpolate with json

I have the following text in my en.yml

update_message: "The user updated device's name to <b>%{name}</b>"

and I have the following json object

{ "user": { "id": 1, "name: "Wagner Junior" } }

The service dynamically resolve the interpolation in the same way as always:

t('update_message', json_object)

but it didn't work.

I want to replace the %{name} in the update_message with the name attribute in my json object, kinda user/name, user.name, user>name, etc. I can't use json_object['name'] because I will have other messages that will receive the json object.

I've tried to use different ways to do this interpolation no success.

Upvotes: 0

Views: 124

Answers (2)

Vasily Kolesnikov
Vasily Kolesnikov

Reputation: 509

I want to replace the %{name} in the update_message with the name attribute in my json object, kinda user/name, user.name, user>name, etc. I can't use json_object['name'] because I will have other messages that will receive the json object.

Let's say your cases dependent on context. Then you could write a function (e.g. method) that will accept the context and the object and return a corresponding value for I18n translation: f(context, object) => value.

f = ->(context, obj) { ... }
name = f.call(context1, { user: { id: 1, name: 'Wagner Junior' } })
=> 'Wagner Junior'
t('update_message', name: name)
=> "The user updated device's name to <b>Wagner Junior</b>"

name = f.call(context2, { user: [:id, 1, :name, 'Wagner Junior'] })
=> 'Wagner Junior'
t('update_message', name: name)
=> "The user updated device's name to <b>Wagner Junior</b>"

But only for know what the context is and how calculation a value from the context should be performed.

Upvotes: 0

Christian
Christian

Reputation: 5521

Rails is expecting a flat hash for the interpolation values, not a nested one, so you can try this:

t('update_message', name: json_object["user"]["name"])

If you have multiple and possibly unknown depth levels, you might want to flatten your hash to receive something like {"user_id" => 1, "user_name" => "Wagner Junior"} you can work with.

Regarding

I can't use json_object['name'] because I will have other messages that will receive the json object.

you didn't specify what these other JSON objects are, how they look like, and how they relate to the other messages. Here's a general idea:

def translate_with_json(key, json)
  if key == 'update_message'
    name = json['user']['name']
  elsif key == 'another_message'
    name = json['another']['name']
  else 
    ...
  end
  t(key, name: name)
end

Upvotes: 0

Related Questions