What is ERB?
A roadmap page that shows a different button for every user
This project's roadmap page, app/views/catalog/courses/index.html.erb, shows "Continue Learning" to someone mid-course and "Start Learning" to someone who hasn't started, through its course card partial, on the same request path. A plain .html file can't do that: every visitor gets the same text. The roadmap's files end in .html.erb, and those three letters are why they can decide instead of just state.
ERB stands for Embedded Ruby: an ordinary HTML file with small pieces of Ruby in it. This project's app/views/public/pages/partners.html.erb, the file ActionController: actions pointed at for four lessons without opening, is one. Here it is trimmed to its simplest shape:
<% if @partners.any? %>
<p><%= t("partners.founding_heading") %></p>
<% end %>
The snippet mixes plain HTML (<p>), a Ruby condition deciding whether that <p> exists, and a Ruby expression whose result is printed inside it. The real file builds the same shape with more markup around it. Lesson 2 draws the line between those two kinds of Ruby; for now the shape only needs to look familiar.
Rendered once per request
ActionController: actions showed that partners runs once per request, from the top, with nothing left from the last visit. The .html.erb file it renders runs on the same clock. Each request to /partners runs the Ruby in partners.html.erb from scratch, using the @tiers, @partners and @inquiry that request's action just set. Lesson 3 shows how a view reads them.
Where this course goes
- Lesson 2 separates ERB's two tags: one prints a result, one only runs code.
- Lesson 3 shows a real view reading an instance variable its action set.
- Lesson 4 covers why Rails escapes that output by default, and
html_safe. - Lesson 5 opens
articles#show, the file every implicit-render lesson in ActionController: actions pointed at. - Lesson 6 reads this project's layout file for one more example.
- Lesson 7 ties the course together and names what comes next.
Keep going with lesson 2
<%= %> vs <% %>: two tags, one difference
Separates <%= %>, which prints a result, from <% %>, which runs conditions, loops and assignments silently.
A free account also gives you the quizzes, your progress and notes, and the discussion.