【问题标题】:What is the way to add translation to an array?向数组添加翻译的方法是什么?
【发布时间】:2012-04-18 19:10:11
【问题描述】:

对不起,如果这真的很容易。但是我尝试了很多方法来添加 I18n,但似乎都不起作用。

这是风景

 =  @event.categories.map(&:name).to_sentence

这是在语言环境中

 #Categories
   categories:
   gastronomy: Gastronomy
   family: Family
   sports: Sports
   scene: Scene
   traditional: Tradition
   music: Music
   party: Party

我设法让翻译工作在表格中,但不是在这里。知道为什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1 internationalization activesupport


    【解决方案1】:

    选项 1

    假设有如下yaml文件结构

    categories:
      gastronomy: Gastronomy
      family: Family
      sports: Sports
      scene: Scene
      traditional: Tradition
      music: Music
      party: Party
    

    现在您可以执行以下操作:

    @event.categories.map{|n| I18n.t("categories.#{n}"}.to_sentence
    

    选项 2

    更好的是,您可以更改 Category 模型以返回本地化名称:

    class Category < ActiveRecord::Base
    
      def name
        key = read_attribute(:name)
        return key if key.blank? # return immediately if nil
        # use the key as value if the localization value is missing
        I18.n("categories.#{key}", :default => key.humanize)
      end
    end
    

    现在,name 方法返回一个本地化值:

    cat.name # localized name
    

    您的原始陈述也可以使用

    @event.categories.map(&:name).to_sentence
    

    选项 3

    使用Globalize3 宝石。观看此screencast 了解更多详情。

    【讨论】:

    • 这是一个很棒的答案!非常感谢!
    • 更新了处理边缘情况的答案。看看吧。
    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 2013-12-26
    • 1970-01-01
    • 2021-07-29
    • 2013-01-04
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多