简体   繁体   English

ROR:本地化消息字符串变量替换

[英]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. 我试图找出在我的ruby on rails应用程序中替换本地化消息字符串中的多个变量/占位符的最佳方法。 When replacing a single placeholder I have used the satisfactory: 当替换单个占位符时,我使用了令人满意的:

In en.yml: url_borked: "The URL: $url could not be loaded." 在en.yml中:url_borked:“无法加载URL:$ url。” In view: t(:url_borked)["$url"] = request.url 在视图中: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: 在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. 我已经尝试过使用String :: sub,但是因为丑陋而对它不满意。 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. 我也考虑过printf函数,但这不适用于本地化,因为占位符的相对位置可能会根据转换而改变。

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. 好吧,我有一个脑波,并且更仔细地查看了I18n :: translate函数,并在其中找到了“插值”功能。

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. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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