Difference between rails label and label_tag

徘徊边缘 提交于 2020-01-05 08:28:54

问题


In rails both label and label_tag seem to work the same. Are there any internal differences on how they are rendered by rails ? And which one is a better to use ?


回答1:


Use f.label when you are inside a form object created with form_for(...) do |f| and want to refer to a model-attribute. If your app is i18n-ed, Rails will use the translation to display the attribute name.

Use label_tag when you are not in a form object. (Or you are in a form object but want to create a dummy label for a non-model attribute.)

All form inputs have these two variants, with and without the _tag suffix, like select and select_tag, etc.




回答2:


I'm assuming you mean just label and not f.label. The difference I have seen between using only label and label_tag is that you cannot set custom labels while using only label i.e if you use

label :name, "My Name:
in the view, it will not render My Name but just Name. But if you use

label_tag :name, "My Name:"


It will render My Name on the display.

来源:https://stackoverflow.com/questions/19704366/difference-between-rails-label-and-label-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!