Ruby On Rails Tips, Tricks and Shortcuts #1: The Content Tag
Writing HTML is a pain in the rear, luckily Rails has a generic helper function aptly named content_tag that will quickly allows us to write any HTML we’d like.
Suppose we have an instance variable @post with an attribute of text, we want to render or text within a <p> element. Traditionally we’d do this like so:
<p class="strong"><%= @post.content %> </p>
With the content_tag helper we can avoid having to worry about opening and closing our HTML and embedded Ruby tags.
The first argument of the content tag is a symbol for the element we want to render. The second argument is the content of our element. Here’s how we can use content_tag to render a <p> elem with the content of our post:
<%= content_tag :p, @post.content, class: 'strong' %>
Using the content tag is also useful when we need to use embedded Ruby multiple times in a single HTML element. For example the two lines of code are equivalent, however the latter is shorter and easier to write:
<div class="alert alert-<%= msg_type %>" > <%= msg %> </div><%= content_tag :div, msg, class: 'alert alert-#{msg_type}' %>
Corey’s Corner Podcast -> https://anchor.fm/coreys-corner
Ruby on Rails E-Commerce Tutorial -> https://www.youtube.com/watch?v=gAXs3xhfHVg
Get Yoked 🍳 -> https://thoughtsandfitness.com
Gardner App Development -> https://gardnerappdev.com