如何在I18n本地化中执行插值?

24

有没有一种方法可以做到这样:

en:
  welcome:
    hello there, #{current_user.first_name}!  It's nice to see you again.

显然那样做行不通,而且在yaml中 "#{" 是无效的字符,因为当我提取它时,该字符串只显示为"hello there, "。

我能做到的最好的方法是:

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

....

t(:welcome).gsub("(name)", current_user.first_name)

但我对此并不狂热...肯定有更好的方法来做这种事情。

1个回答

34

请按照以下方式替换您的en.yml文件:

en:
  welcome:
    "hello there, %{name}!  It's nice to see you again."

并且您的视图应该像这样

<%=t(:welcome, :name=> current_user.first_name) %>

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接