是否存在针对布尔语的I18N翻译?

时间:2011-03-08 05:46:15

标签: ruby-on-rails-3 internationalization

我需要显示"是"或"否"基于表达式是真还是假的各种语言。目前我这样做:

fr.yml:

fr:
  "yes": Oui
  "no": Non

辅助方法:

def t_boolean(expression)
  (expression) ? t("yes") : t("no")
end

ERB:

Valid: <%= t_boolean(something.is_valid?) %>

有没有更好的方法呢?

Rails是否已经有像这样的真/假翻译?

7 个答案:

答案 0 :(得分:37)

在阅读this之后,我得到了启发并想出了这个解决方案:

fr.yml

fr:
  "true": Oui
  "false": Non

ERB:

Valid: <%= t something.is_valid?.to_s %>

<强>更新

对于英语,如果您想使用yesno作为值,请务必引用它们:

en.yml

en:
  "true": "yes"
  "false": "no"

答案 1 :(得分:10)

正如Zabba所说的那样正常,但是如果你试图将真假翻译成是 - 否,引用双方,否则你将真实地转化为真(TrueClass)。

en:
  "true": "yes"
  "false": "no"

答案 2 :(得分:1)

您可以尝试覆盖I18n的默认translate method,委托默认方法进行实际翻译。在初始化程序中使用此代码:

module I18n
  class << self
    alias :__translate :translate #  move the current self.translate() to self.__translate()
    def translate(key, options = {})
      if key.class == TrueClass || key.class == FalseClass
        return key ? self.__translate("yes", options) : self.__translate("no", options)
      else
        return self.__translate(key, options)
      end
    end
  end
end

答案 3 :(得分:1)

# Inside initializer
module I18n
  class << self
    alias :__translate :translate #  move the current self.translate() to self.__translate()
     alias :t :translate
     def translate(key, options = {})
       if key.class == TrueClass || key.class == FalseClass
         return key ? self.__translate("boolean.true", options) : self.__translate("boolean.false", options)
       else
         return self.__translate(key, options)
       end
     end
  end
end

# Inside locale
boolean:
  :true: 'Yes'
  :false: 'No'

# Calling translate
I18n.translate(is_this_my_boolean_column)

使用Rails 3.2.2:)

答案 4 :(得分:0)

请注意,翻译方法已在I18n中设置了别名。

当您为方法设置别名时,实际上是在为方法创建新副本,因此只有在调用 t 方法时才重新定义 translate 方法。 为了使上述代码有效,您也可以使用 t 方法作为别名。

module I18n
  class << self
    alias :__translate :translate #  move the current self.translate() to self.__translate()
    alias :t : translate # move the current self.t() to self.translate()
    def translate(key, options = {})
      if key.class == TrueClass || key.class == FalseClass
        return key ? self.__translate("yes", options) : self.__translate("no", options)
      else
        return self.__translate(key, options)
      end
    end
  end
end

答案 5 :(得分:0)

我更喜欢的其他解决方案:

# Create a helper
def yes_no(bool_value)
  if bool_value
    t(:yes_word)
  else
    t(:no_word)
  end
end

# Add the translations, important that you use " around yes or no.
yes_word: "No"
no_word: "Yes"

# In your views, in my case in slim:
span= yes_no myvalue
# Or ERB
<%= yes_no(myvalue) %>

答案 6 :(得分:0)

对于任何布尔值翻译

我只是喜欢布尔复数黑客

# some_view.html.erb
t(:are_you_ok?, count: (user.is_ok? ? 0 : 1)  ).html_safe

翻译

# locales/en.yml
en:
  are_you_ok?:
    zero: "You are <strong>NOT</strong> ok ! Do something !"
    one: "You are doing fine"

你甚至不需要引用^^。