views:

122

answers:

2

I am trying to work out the best way to replace multiple variables/placeholders within localized message string in my ruby on rails application. When replacing a single placeholder I have used the satisfactory:

In en.yml: url_borked: "The URL: $url could not be loaded." In view: t(:url_borked)["$url"] = request.url

But this is not suitable for multiple placeholders. It looks ugly, and it doesn't actually work e.g:

In en.yml:

url_borked: "The URL: $url is badly formatted, perhaps you meant: $url_clean"

In view:

(t(:url_borked)["$url"] = request.url)["url_clean") = @suggested_url

I have tried using String::sub, but am not happy with that as it ugly. e.g.:

(t(:url_borked).sub("$url", request.url).sub("url_clean", @suggested_url)

It also doesn't work if you want to replace multiple instances of the one placeholder. e.g.:

bad_url: "$url cannot be loaded, please try $url another time"

I have also considered the printf function, but that does not work for localisation as the relative position of the placeholder can change depending on the translation.

Is there correct way to do this message placeholder substitution?

Thanks.

A: 

Why not:

t(:url_borked, :url=>request.url, :url_clean=>@suggested_url)

?

AlexT
Thanks AlexT, you are absolutely right and I feel a little silly for overlooking the obvious. You just beat me to answering my own question so you get the big tick!Cheers.
zizee
A: 

Ok, I had a brainwave and looked at the I18n::translate function a bit more closely and found the "interpolation" functionality within.

e.g.

I18n.t :foo, :bar => 'baz' # => 'foo baz'

Exactly what I needed. Funny that I would work it out after I finally decided to ask the crowd for a solution :-)

Cheers.

zizee