Embedded Ruby (ERb) and RHTML 2020
In Rails, for each action in each controller, there is an associated view source file, called a template. The view is responsible for the presentation of the page. If we want to have a good Model-View-Controller design practices, view code should include everything related to generating the associated HTML output, but not incorporate business logic, direct access to the database, nor generally any direct access to model objects. All of the data it needs is prepared for it by the controller and placed into variables for use by the view.
Rails can render views in various ways. Here, we'll use the most common one, in which the template is called an RHTML file, for Ruby HTML, because it is a mix of both.
When Rails processes a template file, how does rails tell the difference between HTML code that it should just send to the browser and Ruby code that it needs to execute? RHTML solves this by providing hints in the form of special tags to identify pieces of Ruby code.
Ruby code in a view template is enclosed by <% %>. The enclosed text is what is called embedded Ruby or ERb.
However, there's one slight subtlety. Sometimes we may want to write code that provides output to be displayed, and sometimes we have some simple, yet invisible logic needed to construct the page, such as a loop.
If the Ruby code is preceded by just <%, then the code is executed, but its output is NOT inserted into the HTML stream. We'd use this in our example of a loop or a conditional, for instance. So, we might have Ruby code that says something like âif post title is not blankâ. In real code, this would be:
<% if !post.title.blank? %>
The code doesn't produce any output, instead, this statement determines whether or not the lines that follow it will be used or not.
If we want to have the output from the Ruby code inserted into the HTML stream, we add an equal sign after the opening tag, so the symbols that start the embedded Ruby block are less-than symbol, percent, equal sign (<%=). The equal sign indicates that the output of this Ruby code is to be used as HTML.
if we had a variable named title and we wanted its value to be inserted into the HTML, we do this:
<%= title %>
So:
- <% and %> wrap Ruby code whose return value will NOT be output.
- <%= and %> wrap Ruby code whose return value will be output in place of the marker.
- <% and -%> The extra dash makes ERB not output the newline after the closing tag. So,
<div> <% if true -%> Ruby <% end -%> </div>
will produce:<div> Ruby </div>
There are other alternatives to erb:
An Analysis of the State of Haml vs Slim : ruby - Reddit.
For haml with erb - visit Templating with ERB & HAML.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization