rails wonderful content_tag method for easy html markup

I always hate to write basic HTML tags in view files as they are  much more complex to write and the angle brackets with close/open HTML tags make the readability very worst. I became much happy when i come to know that rails is providing wonderful ‘content_tag’ method by default for clean and easy HTML markup implementation.


content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)


Here,
name:   name of html tag
content_or_options_with_block:   content to be placed in html tag(default is nil)
options:   hash for adding html attributes

Examples:
content_tag(:div, "Hello Rails!")
   # => Hello Rails!
content_tag(:div, content_tag(:p, "How Are You?"), :class => "status_msg")
   # =>  <div class="status_msg"><p>How Are You?</p></div>


We can use it as a block by passing the ‘options’ as a second parameter. Eg:


<% content_tag :span, :class => "side_footer" do -%>
    I love Rails!
<% end -%>


I used it in one of my project to make user’s navigation bar :


def user_navigation_bar
 content_tag(:div, :class =>"top_banner") do
   if current_user
     content_tag(:li) { current_user.username}
     content_tag(:li) { link_to("Edit Profile", edit_user_path(:current)) }
     content_tag(:li) { link_to("Logout", logout_path) }
   else
     content_tag(:li) { link_to("Login", login_path) }
     content_tag(:li) { link_to("Signup", new_user_path) }
   end
  end
end


Vow,  it is easy to read with lot of  DRYness. I also like http://haml-lang.com for generating clean, semantic markups.

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically each day to your feed reader.

No comments yet.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)