如何获得模板的当前I18n范围?

时间:2014-05-09 22:17:20

标签: ruby-on-rails ruby-on-rails-4

我有一个功能:

def some_func(current_i18n_scope)
  #...
  name = I18n.t("name",scope:current_i18n_scope)
  #...
end

可在模板中访问:

# app/views/foo/index.html.erb
  ...
  <%= t(".other") %>
  <%= some_func(current_i18n_scope_template) %> 
  ...

# config/locales/foo.yml
en:
  foo:
    index:
      name: Amigo
      other: Other value

如何在模板中获取current_i18n_scope_template并将其作为参数发送给some_func函数?

1 个答案:

答案 0 :(得分:0)

我知道这是一个很老的问题,但这是我如何解决类似的问题。

ActionView :: TranslationsHelper使用私有方法'scope_key_by_partial':

https://github.com/rails/rails/blob/56832e791f3ec3e586cf049c6408c7a183fdd3a1/actionview/lib/action_view/helpers/translation_helper.rb#L123

您可以看到此方法如何使用@virtual_path实例变量(由ActionView :: Context提供)来限定以'。'开头的键。

要简单地获取范围,您可以执行以下操作:

def current_i18n_scope
  @virtual_path.gsub(%r{/_?}, ".") 
end
相关问题