翻译某些字段的干燥方法是什么?

在我的宁静观点中,我有一些重复的片段,例如在节目视图中:

...
<dt><%= t("activerecord.attributes.user.firstname") %></dt>
<dd><%= @user.firstname %></dd>
...

现在,而不是写作 t("activerecord.attributes.user.attr_name") 一遍又一遍地,我只想写 t(:attr_name) (如同 f.label :firstname 在表单视图中)。

基本上,这不是一个问题(至少对于静止视图),因为I18N模块可以查询 controller 推断型号,然后猜测正确的翻译字符串的方法。

我的问题:有人对这种方法有实践经验吗?甚至可以有红宝石吗?或者:我没想到吗?

有帮助吗?

解决方案

我似乎 ActiveModel::Translation#human_attribute_name 做到了(例如 <%= User.human_attribute_name :firstname %>).

其他提示

推荐的方法是将其放入部分(例如 app/views/user/_form.html.erb 甚至 app/views/user/_user.html.erb),然后在名称之前用领先的点::

<dt><%= t(".firstname") %></dt>
<dd><%= user.firstname %></dd>

更多信息: 例子 (从 铁轨敏捷的网络开发); 铁轨文档

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top