表单标签的 Rails i18n 和 yml 结构
根据 ActionView 文档。引用:
标签的文本将默认为属性名称,除非在当前 I18n 语言环境中找到翻译(通过views.labels.
. )或者您明确指定它。
我有一个“用户”模型和注册表。这是相关部分的片段:
<% form_for(@user) do |f| %>
...
<p>
<%= f.label :username %>
<%= f.text_field :username, :class => 'full_width' %>
</p>
...
<% end %>
点隐藏不重要的代码。
据我了解文档,如果我在我的语言环境文件中提供翻译,在这种情况下:dk,我的 dk.yml 看起来像这样:
dk:
views:
labels:
user:
username:
"blahblah"
Rails 应该翻译标签文本并插入“blahblah”而不是“用户名”。
这没有发生,所以我一定错过了什么。任何帮助表示赞赏。
According to the ActionView documentation. Quote:
The text of label will default to the attribute name unless a translation is found in the current I18n locale (through views.labels.<modelname>.<attribute>) or you specify it explicitly.
I have a "user" model and a registration form. Here's a snippet of the relevant part:
<% form_for(@user) do |f| %>
...
<p>
<%= f.label :username %>
<%= f.text_field :username, :class => 'full_width' %>
</p>
...
<% end %>
Dots hide unimportant code.
As I understand the documentation, if I provide a translation in my locale file, in this case :dk, my dk.yml looking like so:
dk:
views:
labels:
user:
username:
"blahblah"
Rails should translate the label text and insert "blahblah" instead of "Username".
This is not happening, so I must have missed something. Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Rails 3.1 中,情况发生了一些变化。
In Rails 3.1 that is a little bit changed.
我想我在这里找到了另一个解决方案。
我的应用程序版本是 2.3.5。我现在已将其更改为 2.3.8,并且
<%= f.label :username %>
现在使用以下翻译:我在这张票中找到了提示:
https://rails.lighthouseapp.com/projects/8994/tickets/745 -form-label-should-use-i18n
I think I found another solution here.
My app was version 2.3.5. I've now changed it to 2.3.8 and
<%= f.label :username %>
now uses the translation in:I found the hint in this ticket:
https://rails.lighthouseapp.com/projects/8994/tickets/745-form-label-should-use-i18n
这是因为您调用的
label
方法不是来自ActionView::Helpers::FormHelper
的方法,而是来自label_tag
的方法代码>ActionView::Helpers::FormTagHelper。form_for
方法通过将_tag
添加到使用的表单助手来重写给定块中的代码。所以您没有查看文档来找到正确的方法!我尚未使用该方法,因为有时字段的标签可能与使用同一模型的多个表单不同,因此我编写了自己的帮助程序。
That's because the
label
method you are calling is not the one fromActionView::Helpers::FormHelper
but is in fact thelabel_tag
method fromActionView::Helpers::FormTagHelper
. Theform_for
method is rewriting the code in the given block by adding_tag
to the used form helpers. So you're not looking at the documentation for the right method!I've not yet used that method, as sometimes the label for a field can be different from multiple forms using the same model, so I've written my own helper.