§2023-02-28
- What is Ruby?, Class Method Doc 3.2
- ERB – Ruby Templating
- An Introduction to ERB Templating
- ri is a tool that allows Ruby documentation to be viewed on the command-line.
ERB is part of the Ruby standard library. You do not need to install any other software to use it. Rails uses an improved version, called Erubis. ri ERB to read the docs
<html>
<body>
<h1>Messages for <%= name %></h1>
<ul>
<% messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</body>
</html>
-
Everything inside the so called ERB tags
<% ... %>
is considered Ruby code -
Everything outside of them is just some static text
-
<%= ... %> the results of the Ruby code
-
imagine stripping everything outside the ERB tags, and the opening and closing tags themselves from the code above. And imagine replacing the = equals sign with puts statements. You’d then end up with this code:
puts name
messages.each do |message|
puts message
end
ERB, when executed, does exactly this, except that = as part of the ERB tag <%= ... %> will not output things to the terminal, but capture it, and insert it to the surounding text (HTML code, in our case) in place of this tag. Ruby code in ERB tags that do not have an equal sign, such as <% ... %> will be executed, but any return values won’t be captured, and just discarded.
ERB recognizes certain tags in the provided template and converts them based on the rules below:
- <% Ruby code -- inline with output %>
- <%= Ruby expression -- replace with result %>
- <%# comment -- ignored -- useful in testing %> (
<% #
doesn't work. Don't use Ruby comments.) - % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
- %% replaced with % if first thing on a line and % processing is used
- <%% or %%> -- replace with <% or %> respectively