FormHelper::label 和 FormTagHelper::label_tag 有什么区别? [英] What is the difference between FormHelper::label and FormTagHelper::label_tag?

查看:31
本文介绍了FormHelper::label 和 FormTagHelper::label_tag 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个处理多个模型的表单.有关如何执行此操作的一些示例,请使用 ActionView::Helpers::FormHelper::标签,有些使用ActionView::Helpers::FormTagHelper::label_tag,我不太明白其中的区别.

I'm writing a form which is dealing with multiple models. Some examples of how to do this use ActionView::Helpers::FormHelper::label, and some use ActionView::Helpers::FormTagHelper::label_tag, and I don't really understand the difference.

在我的特殊情况下,两者似乎都产生相同的输出:

In my particular case, both seem to result in the same output:

<% form_for :post, :url => { :action => 'create' } do %>
  <p>
    <%= label_tag 'post_type' %><br />
    <%= text_field :post, :post_type %>
  </p>
  <p>
    <%= label :post, :parent_post_id %><br />
    <%= text_field :post, :parent_post_id %>
  </p>
  ...

渲染:

  <p>
    <label for="post_type">Post type</label><br />
    <input id="post_post_type" name="post[post_type]" size="30" type="text" />
  </p>
  <p>
    <label for="post_parent_post_id">Parent post</label><br />
    <input id="post_parent_post_id" name="post[parent_post_id]" size="30" type="text" />
  </p>

标签助手似乎更有用,因为大概它可以做一些额外的事情,因为它知道它标记的模型和属性,但我找不到任何支持它的东西.两者之间有实际区别吗?我什么时候应该使用一个助手而不是另一个?

The label helper would seem to be more useful, because presumably there are some extra things it can do because it knows the model and property it's labelling, but I can't find anything to back that up. Is there a practical difference between the two? When should I use one helper instead of the other?

推荐答案

Rails 提供了两种类型的表单助手:专门处理模型属性的和不处理的.*_tag 助手用于创建不依赖于分配给模板的 Active Record 对象的表单标签.

Rails provides two types of form helpers: those that work specifically with model attributes and those that don't. The *_tag helpers are for creating form tags that don't rely on an Active Record object being assigned to the template.

尽管为 label 元素生成的标记如您所示没有区别,但在您的情况下,您应该使用 label 表单助手以与您的使用其他表单助手,因为它会自动将 for 属性设置为关联文本字段元素的正确 ID.

Although there's no difference in the generated markup for a label element as you've shown, in your case you should use the label form helper to be consistent with your use of the other form helpers and because it automatically sets the for attribute to the correct ID of the associated text field element.

这篇关于FormHelper::label 和 FormTagHelper::label_tag 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆