如何在I18n语言环境中执行插值?

pat*_*ick 14 yaml ruby-on-rails ruby-on-rails-3

有没有办法做这样的事情:

en:
  welcome:
    hello there, #{current_user.first_name}!  It's nice to see you again.
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,显然"#{"是yaml中的无效字符,因为当我将其拉出时,该字符串显示为"你好".

我能做的最好的事情就像:

en:
  welcome:
    hello there, (name)!  It's nice to see you again.

....

t(:welcome).gsub("(name)", current_user.first_name)
Run Code Online (Sandbox Code Playgroud)

但我并不为此疯狂......必须有更好的方法来做这种事情.

fel*_*lix 17

像这样替换你的en.yml

en:
  welcome:
    "hello there, %{name}!  It's nice to see you again."
Run Code Online (Sandbox Code Playgroud)

和你的观点一样

<%=t(:welcome, :name=> current_user.first_name) %>
Run Code Online (Sandbox Code Playgroud)

基本上它作为命名参数传递.您可以在Rails Guides 18n Interpolation上找到更多信息