在 Rails 4 中对视图和表单中的字段使用相同的翻译
Using same translation for field in views and forms in Rails 4
我想在 Rails 4 中对视图和表单中的字段使用相同的翻译,所以我阅读了文档 (http://guides.rubyonrails.org/i18n.html#localized-views) 并尝试了一些但失败了,然后我来了此解决方案:
config/locales/en.yml:
en:
hello: "Hello world"
save: "Save"
customers:
description: "Company full legal name"
app/views/customers/_form.html.erb:
...
<div class="field">
<%= f.label :description, (I18n.t :description, scope: :customers) %>
<%= f.text_field :description %>
</div>
...
app/views/customers/show.html.erb:
...
<p>
<strong><%=t :description, scope: :customers %></strong>
<%= @customer.description %>
</p>
...
但感觉有点 "weird" 至少对于我希望 Rails 自己完成的指定范围的部分。
第一次尝试是将其放入 config/locales/en.yml:
en:
helpers:
label:
customer:
description: "Company full legal name"
这在 app/views/customers/_form.html.erb:
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
但是无法获取显示视图的标签。
感觉我在翻译系统的基础上没有从文档中得到什么,有人能给我指出正确的方向吗?谢谢
使用 i18n 需要练习并密切关注运行时上下文。
我建议(临时)安装一个名为 i18n-tasks 的 gem -- 这是一个命令行工具,有助于理解 YAML 中应用程序本地化字符串的必要结构。
一旦您知道 i18n 在哪里寻找字符串,您就可以根据上下文将字符串以正确的顺序放入 YAML 中的正确结构中。
我想在 Rails 4 中对视图和表单中的字段使用相同的翻译,所以我阅读了文档 (http://guides.rubyonrails.org/i18n.html#localized-views) 并尝试了一些但失败了,然后我来了此解决方案:
config/locales/en.yml:
en:
hello: "Hello world"
save: "Save"
customers:
description: "Company full legal name"
app/views/customers/_form.html.erb:
...
<div class="field">
<%= f.label :description, (I18n.t :description, scope: :customers) %>
<%= f.text_field :description %>
</div>
...
app/views/customers/show.html.erb:
...
<p>
<strong><%=t :description, scope: :customers %></strong>
<%= @customer.description %>
</p>
...
但感觉有点 "weird" 至少对于我希望 Rails 自己完成的指定范围的部分。
第一次尝试是将其放入 config/locales/en.yml:
en:
helpers:
label:
customer:
description: "Company full legal name"
这在 app/views/customers/_form.html.erb:
<div class="field">
<%= f.label :description %>
<%= f.text_field :description %>
</div>
但是无法获取显示视图的标签。
感觉我在翻译系统的基础上没有从文档中得到什么,有人能给我指出正确的方向吗?谢谢
使用 i18n 需要练习并密切关注运行时上下文。
我建议(临时)安装一个名为 i18n-tasks 的 gem -- 这是一个命令行工具,有助于理解 YAML 中应用程序本地化字符串的必要结构。
一旦您知道 i18n 在哪里寻找字符串,您就可以根据上下文将字符串以正确的顺序放入 YAML 中的正确结构中。