Which ERB tag should I use?
Sylwia Vargas
Posted on March 30, 2020
Learning Sinatra or Rails comes usually with a great deal of excitement for students of Ruby. Finally, you can develop websites. However, what I see time and again is that students are really confused about when to use which tag. Here’s a little help. Follow the chart above, or find a statement below that describes your needs:
I need just html tags!
For instance, if you just want to write <h1>
to create a new header, you don’t need any erb tags. Yay! This is an example of an html tags alone:
<h1> Hello! </h1>
I need to write more code than html tags and I want this line to be visible!
This, my friend, calls for <%=
, or, how I like to call it, an “angry squid” (if you tilt your head to the left, you’ll see a very upset squid). Remember it as that the squid shoots ink when it’s pissed off and the ink leaves visible stains so whatever you put in between the squid tag will be visible on the page.
For instance, let’s say you have a universe variable and you want to only have its name visible, you’d do it as follows:
<%= @universe.name %>
I need to write more code than html tags but I don’t want this line to be visible!
Okay, you’ve deserved ice-cream, or <%
(if you tilt your head to the right, you’ll see ice-cream on a cone). No one likes to share their ice-cream so it stays hidden, or, the content of the tags doesn’t show on the page.
For instance, you have a database with many universes and to list them on your index page, you need to iterate over them. You don’t want to have the iteration line visible so you’d wanna do the following:
<% @universes.map do |universe| %>
<% end %>
All together now!
And, to give you a full picture, you’d combine html, squid and ice-cream tags:
<ul>
<% @universes.map do |universe| %>
<li> <%= @universe.name %> </li>
<% end %>
</ul
What you see above, is the following:
- you have an unordered list html tag,
- then, you have an ice-cream tag because you don’t want/don’t need its contents to be visible on the page,
- then, you have a list html tag followed by the angry squid tag, which means that its contents will be visible as a list item,
- then you’re just ending the iteration (‘invisible’ line of code),
- and you’re ending the unordered list.
Good luck playing with squids and ice-creams!
Posted on March 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.