帮助i18n在form_for之外翻译模型属性?

时间:2014-01-17 14:56:02

标签: ruby-on-rails

我有一个名为Presentation的模型。它的所有属性都在我的i18n语言环境文件中命名,位于activerecord.attributes.presentation

我想以表格概述的形式为此模型创建索引视图。目前的代码如下所示:

<table class="table">
  <thead>
    <tr>
      <th><%= t('activerecord.attributes.presentation.title') %></th>
      <th><%= t('activerecord.attributes.presentation.default_duration') %></th>
      <th><%= t('activerecord.attributes.presentation.bg_color') %></th>
    </tr>
  </thead>

  <tbody>
    <%= render @presentations %>
  </tbody>
</table>

哪个工作正常,但是必须写出完整的密钥对我来说似乎并不是Rails的方式。如果缺少翻译,或者模型的这种属性不存在,它也不会以任何明显的方式失败。

<%= f.label :title %>?在form_for块内,自动将翻译的属性名称作为标签输出,仅基于符号。是否有任何类型的视图帮助程序以相同的方式工作,但在表单之外?像这样的东西(这不是最好的代码示例,我知道):

<%= attributes_of User do |attr| %>
  <th><%= attr.t :title %></th>
  <th><%= attr.t :default_duration %></th>
  <th><%= attr.t :bg_color %></th>
<% end %>

2 个答案:

答案 0 :(得分:5)

你能做的最好的事情是:

<% I18n.with_options(scope: 'activerecord.attributes.presentation') do |i18n| %>
  <table class="table">
    <thead>
      <tr>
        <th><%= i18n.t :title %></th>
        <th><%= i18n.t :default_duration %></th>
        <th><%= i18n.t :bg_color %></th>
      </tr>
    </thead>

    <tbody>
      <%= render @presentations %>
    </tbody>
  </table>
<% end %>

非常小心:你必须使用 i18n 而非 I18n ,i18n由with_options块产生。
对于其他键,您只需使用 I18n ,但不会强制使用范围。

答案 1 :(得分:4)

您可以使用human_attribute_for方法

Presentation.human_attribute_for :title
相关问题