Passing block for label helper in rails3

I want to create a shortcut with some nested elements. I use a helper tag and try to pass the internal html as a block, but the generated HTML does not look the way I expected. Euroradio:

<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 in the internal html using <%%> markup output, 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 this is my mistake or error in the ActionView label helper. For other assistants, the transmission lock works fine.

Thanks Michal

+6
source share
3 answers

I understand 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 assistant fills in the for attribute for you (using the model object attribute), you do not need it with nested elements.

When you have an open label tag (rather than a self-closing tag) that wraps internal content, the β€œfor” attribute is not needed because the label is obviously associated with its nested content (this is called implicit association).

So this is the expected behavior - it looks like the Rails team intentionally built it that way.

+10
source

Scott Lowe answered correctly, although I would take one more step ... You don’t even need to use the Rails label_tag for this. Just use raw html, for example:

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

If you associate a label with a form element (for example, a radio button):

 <label> <%= f.radio_button :approval_state, 'R' %> Rejected </label> 
+4
source

In Rails 3.2.11, this works 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> 
+1
source

Source: https://habr.com/ru/post/888761/


All Articles