benams
benams

Reputation: 4646

why should I use content_tag instead of "regular" html?

I know that there is an option to use the content_tag function in ruby-on-rails, which helps to generate an html tag. Some rails developers in a company I work with told me that this is the "convenient and proper" way and I should not write a "native" html in order to generate a div for example... Is it true? Is it a kind of rails standard? Does it have something to do with performance issues or render speed?

I attach the codes for my previous code:

<div class="alert alert-<%= key %>"><%= value %></div>  

and the rails function usage

<%= content_tag(:div, value, class: "alert alert-#{key}") %>

The first looks to me pretty, understandable and intuitive - more than the second code.. What do you think about that?

Upvotes: 12

Views: 1983

Answers (3)

ramya
ramya

Reputation: 275

In addition to Project and Rails standards, Security is one more reason why one must use content_tag.

Two quick reason why I feel content_tag is better

  1. View file of Rails is in Embedded Ruby (meaning) HTML page generated from Ruby.Hence, helper method like content_tag serves the purpose of helping you to generate HTML from ERB.

  2. When hardcoded directly with HTML (native style), it is prone to Cross Site Scripting attack (XSS).

Upvotes: 2

starscream_disco_party
starscream_disco_party

Reputation: 2996

It's a helper method to attempt to simplify HTML generation for you. You pass in what you want to use and it spits out the HTML for it. It basically builds it for you, though I never use them, I'd rather write my own because it takes just as long as typing out the helper method call :) @Jesse good call, if this is what your team is using, stick with the convention

Upvotes: 1

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

Being able to use the content_tag helps when you are programmatically generating HTML inside of ruby code, e.g.: helpers and presenters.

In my opinion, I would not normally use content_tags in the layouts and templates of a project -- I don't think it helps coding readability. I do not see any gains for productivity or performance here.

HOWEVER: word of advice: if that's what your team has standardized on -- go with the team.

Upvotes: 10

Related Questions