ERB Intro

View saved

What ERB is

ERB evaluates Ruby inside a template string—useful for HTML emails and simple pages.

Render a template

Use <%= %> to insert values and <% %> for logic without output.

require "erb"

name = "Ada"
template = "Hello, <%= name %>!"
puts ERB.new(template).result(binding)

Escape for HTML later

When rendering user content into HTML, escape properly. Rails helpers do this automatically; in raw ERB, be careful.

require "cgi"
safe = CGI.escapeHTML(name)
puts ERB.new("Hello, <%= safe %>!").result(binding)

ERB tips

  • Keep heavy logic out of templates
  • Pass a binding or use a view object for data
  • Frameworks build on these ideas
  • Partials and layouts come next in web frameworks

Comments

One comment per signed-in account. Comments are saved with this page’s URL.