【问题标题】:How to use i18n translate method with Draper gem?如何将 i18n 翻译方法与 Draper gem 一起使用?
【发布时间】:2011-10-19 10:28:40
【问题描述】:

我使用 Draper gem 来装饰我的模型。这里我有非常经典的设置:

# app/decorators/subject_decorator.rb
class SubjectDecorator < ApplicationDecorator
  decorates :subject

  def edit_link
    h.link_to(h.t('.edit'), '#')
  end
end

我使用 i18n 进行国际化。但是当我运行它时,我得到:

Cannot use t(".edit") shortcut because path is not available

所以我想知道以前是否有人这样做过?它应该很简单。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 internationalization decorator


    【解决方案1】:

    问题是您不能在装饰器中利用lazy lookup,因为它们没有任何上下文来确定视图文件级别(索引、显示、编辑等)。所以开箱即用,您只需要拼出整个内容,例如 t('subjects.show.edit') 或其他任何内容。

    这就是我最终要做的,以使其对我有所帮助。

    class ApplicationDecorator < Draper::Base
      def translate(key, options={})
        if key.to_s[0] == '.'
          key = model_class.to_s.downcase.pluralize + key
        end
    
        I18n.translate(key, options)
      end
      alias :t :translate
    end
    

    这不会让您获得完整的subjects.show.edit 参考,您只会获得subjects.edit,但对我来说这似乎总比没有好。

    【讨论】:

    • 使用model_name.i18n_key + key可能会更好。
    【解决方案2】:

    在你的代码中你必须使用:

    I18n.t('mylabelkey')
    

    试一试......它应该可以工作

    【讨论】:

      【解决方案3】:

      您所要做的就是将它添加到装饰器类的顶部...

      include Draper::LazyHelpers
      

      ...它处理许多最常见的辅助方法,包括 i18n 的东西。您也可以放弃在 draper 类中编写所有那些“h”。

      【讨论】:

        猜你喜欢
        • 2019-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-08
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多