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)
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>
<% content_tag :span, :class => "side_footer" do -%>
I love Rails!
<% end -%>
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
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>