Passing block to label helper in rails3

2019-02-17 05:12发布

I want to create label tag with some nested elements. I am using label helper and trying to pass inner html as block but generated HTML doesn't look as I expected. ERB:

<span>Span element</span>
<%= label("object", "method") do %>
  <span>Inner span</span>
<% end %>

HTML output:

<span>Span element</span> 
<span>Inner span</span> 

<label for="object_method">
<span>Span element</span> 
  <span>Inner span</span> 
</label>

When I pass inner html using <% %> markups output is as it should be:
ERB:

<span>Span element</span>
<%= label("object", "method") do %>
  <% raw '<span>Inner span</span>' %>
<% end %>

HTML output:

<span>Span element</span>
<label for="object_method">
  <span>Inner span</span>
</label>

I am wondering if it is my mistake or bug in ActionView label helper. For other helpers block passing works fine.

Thanks, Michał

3条回答
看我几分像从前
2楼-- · 2019-02-17 05:21

My understanding is that you need to use the label_tag helper in this case:

<%= label_tag "my_label_name" do %>
  <span>Inner span</span>
<% end %>

The reason for this is that although the form label helper fills out the "for" attribute for you (using your model object attribute), you don't need it with nested elements.

When you have an open label tag (rather than self-closing), that wraps the inner content, the "for" attribute is not needed, because the label is obviously associated with its nested content (this is known as implicit association).

So, this is expected behaviour - it looks like the Rails team have deliberately built it this way.

查看更多
再贱就再见
3楼-- · 2019-02-17 05:23

Scott Lowe's answer is correct, although I'd take it one step further... You don't even need to use the Rails label_tag for this. Just use raw html like so:

<label>
  <span>Inner span</span>
</label>

If you are associating the label with a form element (like a radio button):

<label>
  <%= f.radio_button :approval_state, 'R' %>
  Rejected
</label>
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-17 05:23

In Rails 3.2.11 this is working for me:

<span>Span element</span>
<%= label :item, :method do %>
  <span>Inner span</span>
<% end %>

Result:

<span>Span element</span>
<label for="item_method">
  <span>Inner span</span>
</label>
查看更多
登录 后发表回答