ERBHow Embedded Ruby Is Used to Render HTML
Understanding how ERB work can be a bit confusing at first. This page aims to explain it in straightforward terms using a simple example.
Imagine that you have an app that stores song lyrics, and you want a page that prints the lyrics to a particular song. Instead of making a different HTML.ERB view for every song (which would be awful, of course), you want to have one template HTML.ERB that is parameterized such that it can be used to print any song’s lyrics.
Here is just such an HTML.ERB view:
1 | <h1><%= title %></h1> |
2 | |
3 | <ul> |
4 | <% lyrics.each do |l| %> |
5 | <li><%= l %></li> |
6 | <% end %> |
7 | </ul> |
This HTML.ERB generates plain old HTML code such that there is a heading (h1
) with the song title and a bullet list (ul
) where each bullet item (li
) is a lyric in the song. The lyrics
variable references an array of strings, with each string having a different line of the song lyrics.
When a Rails controller renders this HTML.ERB code, the HTML.ERB code effectively behaves like the following Ruby code, where the write
function concatenates its string argument onto the end of the plain old HTML string to be output:
1 | write('<h1>') |
2 | write(title) |
3 | write('</h1>\n') |
4 | write('\n') |
5 | write('<ul>\n') |
6 | lyrics.each do |l| |
7 | write(' <li>') |
8 | write(l) |
9 | write('</li>\n') |
10 | end |
11 | write('</ul>\n') |
In the above Ruby code, notice how all the plain old HTML code was wrapped in write
statements. In contrast, the embedded Ruby code (<% ... %>
) is simply inserted between the write
statements. The embedded Ruby code inside the element, <%= ... %>
(note the =
sign), was additionally wrapped in a write
statement that will write whatever value is returned by the embedded Ruby code.
So, imagine the above HTML.ERB was rendered with the lyrics
array set as follows:
1 | title = 'Go Tigers Go' |
2 | lyrics = [ |
3 | 'Go on to victory', |
4 | 'Be a winner through and through', |
5 | 'Fight Tigers Fight', |
6 | '\'Cause we\'re going all the way' |
7 | ] |
The generated HTML would look like this:
1 | <h1>Go Tigers Go</h1> |
2 | |
3 | <ul> |
4 | <li>Go on to victory</li> |
5 | <li>Be a winner through and through</li> |
6 | <li>Fight Tigers Fight</li> |
7 | <li>'Cause we're going all the way</li> |
8 | </ul> |
Further Reading
For more info on ERB, see the official Ruby documentation: https://ruby-doc.org/stdlib-3.1.2/libdoc/erb/rdoc/ERB.html