spierepf
spierepf

Reputation: 2924

In rails, what distinguishes label from label_tag?

I'm noticing in my rails views, some views use (helpers?) named xxx and other places use ones named xxx_tag?

Can anyone outline the difference between the two and how I can know which to use in a given case?

Upvotes: 3

Views: 1838

Answers (2)

Ajey
Ajey

Reputation: 8202

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

Upvotes: 2

pat
pat

Reputation: 16226

label (and equivalents) can be called on a form builder (the object yielded when calling form_for), and so can be aware of the model instance the form's focused on, will automatically link it via the for attribute to the appropriate input, and may use I18n translations.

label_tag (and equivalents) isn't tied to a form, and is used for generating the label HTML tag at a more basic level. It's not as smart, you have to give it all the attributes you want it to have, but sometimes that's what you need.

Upvotes: 2

Related Questions