Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 509
benams Avatar asked Jul 23 '12 14:07

benams


2 Answers

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.

like image 199
Jesse Wolgamott Avatar answered Nov 03 '22 23:11

Jesse Wolgamott


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).

like image 2
ramya Avatar answered Nov 04 '22 00:11

ramya