skip to content

ERB Escaping & Lookup

ERB's <%= %> escapes output through SafeBuffer unless you reach for html_safe, raw or <%== %>, and Rails finds each template by action, format, variant and handler. Interviewers probe both as traps.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails ERB template, how do <% %>, <%= %> and <%# %> differ, and what does <%= %> do to its value?

level: juniorimportance: must knowfreq 72%

answer

  1. run, print, or ignore
  2. <%= %> escapes unless html_safe
  3. nil prints nothing
  4. puts goes to the server, not the page
  5. <%- and -%> trim whitespace

basics

~20 s

In a Rails ERB template, <% %> runs Ruby without output, <%= %> runs it and appends the result to the page HTML-escaped unless it is html_safe, and <%# %> is a comment that never runs.

solid answer

~30 s

`<% %>` executes Ruby and discards the value, so it is used for `if`, `each` and assignments. `<%= %>` executes Ruby, converts the result to a string and appends it to the output buffer; Action View's buffer HTML-escapes `&`, `<`, `>`, `"` and `'` unless the value is `html_safe`, and a `nil` adds nothing. `<%# %>` is a comment, so the code inside never runs. `<%-` and `-%>` trim surrounding whitespace. Two classic slips: `<%= @members.each do |m| %>` prints the collection after the loop, and `puts` inside `<% %>` writes to the server's standard output, not to the page.

code

erb · 12 lines
erb
<%# app/views/profiles/show.html.erb %>
<h1><%= @member.display_name %></h1>

<% if @member.bio.present? -%>
  <p class="bio"><%= @member.bio %></p>
<% end -%>

<ul>
  <% @member.interests.each do |interest| %>
    <li><%= interest.name %></li>
  <% end %>
</ul>

go deeper

for a junior

Know which tag runs code, which prints and which is a comment, and that printed text is escaped by default.

for a middle

Explain the buffer: nil skipped, to_s, html_safe? checked, ERB::Util.html_escape applied, and why block helpers need <%= %> while loops do not.

for a senior

Use the escape-by-default rule in review: every html_safe, raw and <%== %> is a deliberate opt-out that needs a reason next to it.

for a principal

Treat escape-by-default as a team policy: lint or review rules that flag opt-outs keep templates safe as the codebase and the number of authors grow.

## Three tags, three jobs An `.html.erb` file in a Rails app is HTML with embedded Ruby. Action View compiles each template once into a Ruby method that writes into an **output buffer** (an `ActionView::OutputBuffer`), and the ERB tags decide what reaches that buffer. | Tag | Runs the Ruby? | Writes to the page? | Typical use | |---|---|---|---| | `<% %>` | yes | no | `if`, `each`, local assignments | | `<%= %>` | yes | yes, escaped unless `html_safe` | attributes, helper calls, block helpers that return markup | | `<%# %>` | no | no | comments for the next reader | | `<%== %>` | yes | yes, never escaped | rare; covered with `raw` and `html_safe` | ## What `<%= %>` actually does The compiled template calls the buffer's `<<` (aliased `append=`) with the expression's value. That method: 1. skips the value entirely when it is `nil`, so `<%= @member.nickname %>` with no nickname prints nothing; 2. calls `to_s` on everything else; 3. checks `html_safe?` on the result and, when it is false, runs `ERB::Util.html_escape` over it, turning `&`, `<`, `>`, `"` and `'` into entities; 4. appends the result. So a member bio stored as `<b>Hi</b>` in a plain String renders as the visible text `<b>Hi</b>` (the browser receives `&lt;b&gt;Hi&lt;/b&gt;`). Values that come back from Rails helpers such as `link_to` or `tag.p` are already `ActiveSupport::SafeBuffer` instances marked safe, so they are appended as markup, while their own arguments were escaped when the helper built them. Numbers report `html_safe?` as true and are appended unchanged. ## Loops and block helpers Control flow belongs in `<% %>`: - `<% @members.each do |member| %> ... <% end %>` runs the loop; the body's own `<%= %>` tags print each item. - `<%= @members.each do |member| %>` also runs the loop, but `each` returns the collection, and that return value is then printed after the last item as its string form. It is a common junior-level bug. - Helpers that take a block and **return** markup, such as `form_with` or `tag.div do ... end`, are called with `<%= ... do %>` so their result reaches the page; called with `<% %>` they build the markup and throw it away. ## Comments, whitespace and `puts` - `<%# %>` is a comment; whatever is inside is not evaluated, so it is the safe way to leave a note or switch off a line. - `<%-` and `-%>` can be used in place of `<%` and `%>` to suppress the whitespace and newline around a tag; Rails' ERB handler runs with trim mode `"-"` by default, so they are understood out of the box. - In a `.text.erb` template (MIME type `text/plain`, common for mailers) Rails switches HTML escaping off for every `<%= %>`, because entities would be wrong in plain text; the handler's `escape_ignore_list` defaults to `["text/plain"]`. - `puts` or `print` inside `<% %>` writes to the Ruby process's standard output, which is the server's terminal or container log, never the rendered page. Only what is appended to the buffer reaches the response. ## A short worked example In a dating app's profile page, `<% if @member.bio.present? %>` decides, `<%= @member.bio %>` prints the bio with any markup shown as text, and `<%# TODO: show badges %>` is ignored. If the bio is user-written, that default escaping is exactly what keeps a `<script>` tag in it from running. ## Mistakes interviewers like to show - `<% link_to "Edit", edit_profile_path(@member) %>` renders nothing: the helper builds the link and the `<% %>` tag throws it away. - `<%= @member.update(seen: true) %>` prints `true` into the page and also writes to the database from a template, which belongs in the controller. - `<div title="<%= @member.tagline %>">` is safe because `"` and `'` are escaped too, so a tagline cannot close the attribute. HTML escaping is the right encoding for element text and quoted attributes; values placed in a `<script>` block or a URL need their own handling, such as `json_escape` for JSON embedded in a script. - Building HTML in Ruby with `+` on plain strings and printing it with `<%= %>` shows the tags as text, which tempts developers into `raw`; the real fix is a helper that returns markup. ## Why the default matters Because escaping is the default and opting out is explicit (`html_safe`, `raw`, `<%== %>`), a code review can find every place untrusted text might be emitted as markup by searching for those three spellings. A view that only uses `<%= %>` on plain strings cannot inject markup by accident.

  • Why does `<%= form_with model: @member do |f| %>` use the equals sign while `<% @members.each do |m| %>` does not?
    `form_with` builds and returns the form markup as an html_safe string, so it has to be appended with `<%= %>` or the form is built and discarded. `each` returns the collection itself; printing that would dump its string form after the loop, so the loop line uses `<% %>` and only the body prints.
  • A Rails view prints `<%= @member.bio %>` and visitors see the text `&lt;b&gt;` where the member typed `<b>`. What happened?
    The text was escaped twice: something stored or built the bio with entities already in it, and `<%= %>` escaped the ampersands again because the string was not html_safe. The fix is to store the raw text and let the view escape once, not to switch to `raw`.

  • <%= %> outputs the stored string verbatim, markup included.
  • puts inside <% %> writes its text into the rendered page.
  • <%# %> hides the output but still runs the Ruby inside it.
  • A loop line needs <%= %> on its each call so the body prints.
  • A nil value inside <%= %> prints the word nil.
open as a page

In Rails views, what does String#html_safe actually do, and how do raw and <%== %> relate to it and to SafeBuffer?

level: middleimportance: must knowfreq 62%

basics

~10 s

In Rails, String#html_safe wraps the string in an ActiveSupport::SafeBuffer marked trusted, without escaping or cleaning anything. raw(x) is x.to_s.html_safe, and <%== %> appends a value unescaped; all three only switch escaping off.

open as a page

In a Rails view, how does sanitize decide which tags and attributes of a member bio survive, and how do strip_tags and strip_links differ?

level: middleimportance: should knowfreq 45%

basics

~10 s

Rails' sanitize keeps only tags and attributes on an allowlist, removes other elements but keeps their text, drops unsafe URL protocols and returns an html_safe string. strip_tags removes every tag; strip_links removes only links.

open as a page

In Rails, how does Action View turn ProfilesController#show into a template file, and what does each part of show.html.erb mean?

level: middleimportance: should knowfreq 42%

basics

~20 s

Rails' Action View searches each view path, app/views first, under the controller's prefixes, such as profiles then application, for a file named after the action, filtered by locale, format, variant and handler: show.html.erb is action show, format html, handler erb.

open as a page

A Rails helper calls gsub on a sanitized member bio and the page now shows escaped tags; how do SafeBuffer's string methods, + and safe_concat explain it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

ActiveSupport::SafeBuffer's transforming methods such as gsub, sub and upcase return a plain String, so <%= %> escapes the sanitized markup again. Its +, << and % escape unsafe arguments, and safe_concat raises SafeConcatError on an unsafe buffer.

open as a page

For a dating app's phone screens, how does Rails choose profiles/show.html+phone.erb over show.html.erb, and what happens when no phone file exists?

level: seniorimportance: should knowfreq 22%

basics

~20 s

When the controller sets request.variant to :phone, Rails' template lookup requests that variant and ranks show.html+phone.erb above show.html.erb; if no +phone file exists, the variant-less template matches and renders. With no variant set, +phone files are never chosen.

open as a page