【问题标题】:What does the percent sign mean in Yaml?Yaml 中的百分号是什么意思?
【发布时间】:2012-05-11 01:28:54
【问题描述】:

我注意到在 i18n rails guide 中,它们有以下代码:

en:
  activerecord:
    errors:
      template:
        header:
          one:   "1 error prohibited this %{model} from being saved"
          other: "%{count} errors prohibited this %{model} from being saved"
        body:    "There were problems with the following fields:"

%{...} 是什么意思?这与#{...} 有何不同?

【问题讨论】:

    标签: ruby-on-rails internationalization yaml


    【解决方案1】:

    如果您再阅读指南,您会看到Passing variables to translations 部分:

    您可以在翻译消息中使用变量并从视图中传递它们的值。

    # app/views/home/index.html.erb
    <%=t 'greet_username', :user => "Bill", :message => "Goodbye" %>
    
    # config/locales/en.yml
    en:
      greet_username: "%{message}, %{user}!"
    

    Interpolation 部分:

    在许多情况下,您希望将翻译抽象化,以便将变量插入到翻译中。为此,I18n API 提供了插值功能。

    除了:default:scope 之外,传递给#translate 的所有选项都将被插值到翻译中:

    I18n.backend.store_translations :en, :thanks => 'Thanks %{name}!'
    I18n.translate :thanks, :name => 'Jeremy'
    # => 'Thanks Jeremy!'
    

    所以%{...} 的东西与 YAML 没有任何关系,这是 I18n 在消息中处理变量插值的方式。

    【讨论】:

    • 更重要的是……这只是字符串插值。 'foo_%{h}' % {h: 'bar'} 返回'foo_bar'
    • @Mallanaga 但问题是关于%{...}#{...}。后者是 Ruby 字符串插值,前者是通过sprintfString#% 别名运行时“插值”(最好称为“替换”IMO)。
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2013-01-31
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多