简体   繁体   English

将块传递到rails3中的标签助手

[英]Passing block to label helper in rails3

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. 我正在使用标签辅助程序,并尝试将内部html作为块传递,但生成的HTML看起来不符合我的预期。 ERB: ERB:

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

HTML output: HTML输出:

<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: 当我使用<%%>标记传递内部html时,其输出应为:
ERB: ERB:

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

HTML output: HTML输出:

<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. 我想知道这是我在ActionView标签助手中的错误还是错误。 For other helpers block passing works fine. 对于其他助手,阻止传球效果很好。

Thanks, Michał 谢谢,Michał

My understanding is that you need to use the label_tag helper in this case: 我的理解是,在这种情况下,您需要使用label_tag帮助器:

<%= 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. 这样做的原因是,尽管表单标签帮助器为您填写了“ for”属性(使用模型对象属性),但您不需要嵌套元素。

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). 当您有一个打开的标签标签(而不是自动关闭的标签)包装内部内容时,不需要“ for”属性,因为标签显然与其嵌套内容相关联(这称为隐式关联)。

So, this is expected behaviour - it looks like the Rails team have deliberately built it this way. 因此,这是预期的行为-看起来Rails团队已故意以此方式构建它。

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. 尽管我将更进一步,Scott Lowe的答案是正确的……您甚至不需要为此使用Rails label_tag。 Just use raw html like so: 像这样使用原始html:

<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>

In Rails 3.2.11 this is working for me: 在Rails 3.2.11中,这对我有用:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM