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