Why should I use content_tag instead of the "normal" html?

I know that it is possible to use the content_tag function in ruby-on-rails, which helps to generate the html tag. Some rail developers in the company I work with told me that this is a "convenient and correct" way, and I should not write "native" html to generate a div, for example ... Is this true? Is this some kind of rails? Does this have anything to do with performance or rendering speed issues?

I am attaching codes for my previous code:

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

and using the rails function

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

The first look at me is pretty clear and intuitive - more than the second code. What do you think about this?

+7
source share
3 answers

The ability to use content_tag helps when you programmatically generate HTML inside ruby ​​code, for example: helpers and facilitators.

In my opinion, I would not use the content content_tags in the project layouts and templates - I do not think this helps the reader to read. I do not see any performance benefits or performance here.

HOWEVER: a word of advice: if this is what your team standardized, go with the team.

+8
source

This is a helper method to try to simplify HTML generation for you. You pass what you want to use and it spits out HTML for it. It basically builds it for you, although I never use them, I would rather write my own because it takes as long as it prints a call to the helper method :) @Jesse is a good call if that is what your team uses with agreement

+1
source

In addition to Project and Rails standards, security is another reason to use content_tag.

Two quick reasons why I feel content_tag is better

  • The Rails file viewer is located on the embedded Ruby (i.e.) HTML page generated from Ruby.Hence, a helper method such as content_tag serves to help you generate HTML from ERB.

  • When hard-coded directly from HTML (native style), it is susceptible to Cross Site Scripting (XSS) attacks.

+1
source

All Articles