开发者

Rails i18n and yml structure for form labels

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 understa开发者_开发百科nd 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.


In Rails 3.1 that is a little bit changed.

<% form_for @post do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>

en:
  helpers:
    label:
      post:
        title: 'Customized title'


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:

dk:
  activerecord:
    attributes:
      user:
        username:

I found the hint in this ticket:

https://rails.lighthouseapp.com/projects/8994/tickets/745-form-label-should-use-i18n


That's because the label method you are calling is not the one from ActionView::Helpers::FormHelper but is in fact the label_tag method from ActionView::Helpers::FormTagHelper. The form_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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜