1.11. Views

ActionView templates can be written in three ways. If the template file has an .erb (or .rhtml) extension then it uses a mixture of ERb (included in Ruby) and HTML. If the template file has a .builder (or .rxml) extension, then Jim Weirich’s Builder::XmlMarkup (http://api.rubyonrails.org/classes/Builder/XmlMarkup.html) library is used. If the template file has a .rjs extension, then it will use ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.

1.11.1. Using Variables with ERb

You trigger ERb using embeddings, such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the following loop for names:

<b>Names of all the people</b>
<% for person in @people %>
  Name: <%= person.name %><br/>
<% end %>

The loop is set up in regular embedding tags <% %>, and the name is written using the output embedding tag <%= %>. This is not just a usage suggestion. Regular output functions like print or puts won’t work with ERb templates. So, this would be wrong:

Hi, Mr. <% puts "Toad" %>

If you absolutely must write from within a function, you can use the TextHelper concat.

<%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.

1.11.2. Layouts and Templates

One of the great benefits of using the Rails framework is the ability to use layouts. A layout defines the surroundings of an HTML page. It’s the place to define the common look and feel of your final output. Layout files ...

Get Rails Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.