简体   繁体   中英

ROR: Localised Message String Variable Substitution

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 eg:

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. eg:

(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. eg:

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.

Why not:

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

?

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

eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM