ERB (with Rails)

Intro to ERB

  • “Embedded Ruby”
  • One of a class of ‘template languages’
  • There are many
  • They do a simple job (used to be called “mail merge”)
What it does
  • Erb file without any `` blocks remains unchanged
  • <% %> must contain legal ruby code!
  • The code between the angle brackets is evaluated.
  • *And only in the case of <%= %> it’s inserted into the resulting text
Example
 1<% %w(Jones Hickey Salas Madeiras).each do |name| %>
 2  ----
 3  Dear Mr. <%= name %>,
 4  I am writing to let you know that I have moved, and my new
 5  address is 1 Main Street, San Fransisco, CA. Please make
 6  a note of it.
 7
 8  Sincerely,
 9
10  Tom
11  -----
12<% end %>

How it works with Rails

  • ERBs are used primarily in views (also known as view templates in rails)
  • Rails has numerous “helper” methods that work very nicely with erb
  • In “routes.rb”: resource or get or path or other command “automatically” defines one or more helpers.
  • In the example below, “sessions_path” was generated by the resources :sessions line in routes.rb
  • ** Reference:** Rails Form Helpers
Example
 1  <% form_for(:sessions, url: sessions_path) do |f|  %>
 2      <div>
 3        email: <%= f.text_field :email %>
 4      </div>
 5      <div>
 6        password: <%= f.password_field :password %>
 7      </div>
 8      <%= f.submit "Sign in" %>
 9  <% end %>
10