Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 134 ยท Standard Library

ERB Templates

Learn ERB, Ruby's built-in template engine - output and code tags, loops, trim modes, passing data with binding and result_with_hash, HTML escaping, error line numbers and safe usage.

A template is a text document with holes in it. Instead of building a long string with + and #{}, you write the document as it should look and mark the places where Ruby code supplies the data. Reports, emails, configuration files, HTML pages and generated source code are all natural fits. The template engine that ships with Ruby is ERB (Embedded Ruby), and it is the engine behind Rails views as well. Learn it once and you can read templates in countless projects.

ERB is tiny: almost everything you need fits in four kinds of tags and one method call. The craft is in the details: controlling whitespace, giving the template its data, escaping HTML, and finding the line that broke. This lesson covers all of it. It builds on strings and blocks, and the data-passing part uses ideas from Closures and Binding.

The four tags

Ruby Output tags, code tags and comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • <%= expression %> evaluates the expression and inserts to_s of the result.
  • <% code %> runs Ruby but inserts nothing: use it for if, each, assignments.
  • <%# comment %> is removed.
  • <%% produces a literal <%.

ERB.new(text) compiles the template. result(binding) runs it and returns the finished string. binding (see below) is how the template sees your local variables. Blocks work across tags: <% items.each do |item| %> ... <% end %> repeats everything between the two tags for every item.

You may have noticed the output contains empty lines where the code tags were. That is the next topic.

Whitespace and trim modes

A line holding only <% ... %> leaves behind its newline, so loops produce blank lines. ERB can trim them if you pass trim_mode:. Here is the same template in four modes, printed with inspect so every newline stays visible:

Ruby What each trim mode removes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The modes, in practice:

  • nil (default): nothing is trimmed. Blank lines appear.
  • "<>": a line that begins with <% and ends with %> loses its newline. Works well for the loop above, but a line such as * <%= i %> is kept, because it does not start with a tag.
  • ">": every newline directly after any %> is removed. Often too much: * a* bdone shows the damage.
  • "-": you decide. <%- removes the indentation in front of the tag, and -%> removes the newline after it. The output of the <ul> example is perfectly indented, even though the template code is indented too. This is the most explicit mode and the one most hand-written templates use.
  • "%": a line starting with % is Ruby code (like <% %>), and %% at the start is a literal %. Handy for shell-script-like templates.

Combine them as a string: trim_mode: "%<>" or "%-". When you are unsure, print result.inspect and look at the newlines.

The old positional form ERB.new(text, nil, "-") was removed. Calling it raises ArgumentError (wrong number of arguments (given 3, expected 1)). Always use the keyword trim_mode:.

Giving the template its data

A template is evaluated like code, so it needs somewhere to look up names. There are three common ways to provide them.

1. A binding

binding is an object that captures the local variables and self at the point where you call it. Passing it to result makes the template see them as if the template were written in your method. The example above did that.

2. A hash of variables

result_with_hash creates a clean scope that has only the names you pass:

Ruby result_with_hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is the safest choice for a plain data template: the template can use only what you pass, not your other local variables. A name that you did not pass (or misspelled) is an error:

Ruby A misspelled variable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You get a NameError with the message undefined local variable or method 'nme' for main, plus a Did you mean? name hint. The backtrace names the template as (erb) and shows the line inside it. Unlike some template languages, ERB does not quietly print an empty string for a missing value, which makes bugs easy to catch.

3. An object: instance variables and methods

Most real code wraps the template in a class so that it can use instance variables (@title) and helper methods. The binding of a method inside the object gives the template all of them:

Ruby A template inside a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside render, binding captures self (the report), so the template can read @title and call the private helpers money and total directly. The template is compiled once into a constant and reused, which is faster than parsing it for every call. This "template object plus view class" shape is how view layers in frameworks are built.

If the template lives in a file, read it: ERB.new(File.read("report.erb"), trim_mode: "-"). The runner has no templates on disk, so we use heredocs.

Escaping HTML

ERB inserts values exactly as they are. If those values come from users and the output is HTML, a name such as <script>steal()</script> becomes a real script on your page: a cross-site scripting (XSS) hole. ERB itself never escapes anything; you do it with ERB::Util.html_escape (alias h).

Ruby html_escape and url_encode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

h converts <, >, &, " and ' into HTML entities, so the text is displayed rather than executed. url_encode (u) percent-encodes a value for use inside a URL (see URI and Networking Basics). Use the right escape for the right place: h for HTML text and attributes, u for URL parts, and never rely on one for the other.

result_with_hash runs in a fresh scope in which the include ERB::Util at the top of your script does not apply, so inside it h is not available. When a template needs helpers, give it a class that includes or defines them, as in the Report example, or here:

Ruby Helpers in a view class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

ERB is not a sandbox. A template can run any Ruby code, so never render a template whose text comes from an untrusted user: they could read files or run commands (this attack is called server-side template injection). Untrusted people may supply data for your templates, never the template itself. If users must write templates, use a restricted language such as Liquid.

When a template breaks

Errors inside a template point to the template, not to a file you have on disk. Give the template a name with filename= so that backtraces say where the problem is:

Ruby Line numbers and syntax errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The error line page.erb:2:in 'Integer#/' tells you the problem is on line 2 of the template. A SyntaxError is a ScriptError, not a StandardError: a bare rescue => e does not catch it, so name it, as above. ERB#src is the secret of how ERB works: it compiles the template into a small Ruby program that appends text to a buffer (_erbout) and then evaluates it. Seeing it helps when a whitespace puzzle will not go away.

Practical patterns

Text generation

ERB is not just for HTML. Any text format works: a changelog, a SQL migration, a .gitignore, a config file, source code in another language.

Ruby Generating a config file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Layout and partials

A "partial" is a template rendered inside another. In plain ERB, call result from within a method that the template can reach:

Ruby A layout with a partial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Here content produces the inner HTML, already escaped item by item, and the layout inserts it without escaping again (escaping it twice would show &lt;ul&gt;). Deciding who escapes what, and when is the main design problem of any template system; frameworks automate it with "safe string" markers, while plain ERB leaves it to you, so be deliberate.

Sibling tools

  • Rails' ERB (Action View) is ERB with automatic HTML escaping on <%= %>, helpers and caching (read-only here; see Ruby on Rails Overview).
  • Erubi is a faster engine with the same syntax, used by Rails; Haml and Slim (third-party gems, not available here) use indentation instead of tags.
  • For one-off string formatting, format, heredocs and string interpolation are lighter than ERB. Reach for ERB when the template is long, has loops, or comes from a file that non-programmers edit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tag inserts the value of an expression into the output?

    <%= %> evaluates the expression and inserts its to_s. <% %> only runs code, <%# %> is a comment and <%% produces a literal <%.
  2. 2. A loop written as <% items.each do |i| %> on its own line leaves a blank line in the output. What fixes this?

    Trim modes remove the newlines after code tags. With "-" you mark exactly which tags trim, with "<>" every line that starts with <% and ends with %> is trimmed.
  3. 3. Why is ERB.new("<p><%= comment %></p>") dangerous when comment comes from a user?

    Plain ERB does no escaping. Wrap values in h(...) (ERB::Util.html_escape) when producing HTML.
  4. 4. What does template.result_with_hash(name: "Ada") give the template access to?

    result_with_hash builds a fresh scope with just those names, so the template cannot see anything else. result(binding) shares the caller's scope.
  5. 5. How do you get readable error locations like page.erb:2 from a template?

    Without a filename the backtrace shows (erb). Setting filename= makes the errors point to your template name and the line within it.

Summary

  • ERB has four tags: <%= %> output, <% %> code, <%# %> comment and <%% literal; ERB.new(text, trim_mode: "-").result(binding) renders.
  • trim_mode: controls whitespace: "-" is explicit (-%> and <%-), "<>" trims whole-tag lines, "%" enables % lines. Check with result.inspect.
  • Provide data with binding (caller's variables or an object's instance variables and methods) or with result_with_hash for a clean scope.
  • ERB never escapes: use h for HTML and u for URLs, and decide who escapes in layouts and partials.
  • Set filename= for useful error lines; SyntaxError is not caught by a plain rescue; ERB#src shows the generated Ruby.
  • ERB runs arbitrary Ruby: never render templates written by untrusted users.

Next: StringIO and Streams