Section 5.0. Introduction


5.0. Introduction

Action View serves as the presentation or view layer of the MVC (model view controller) pattern. This means that it's the component responsible for handling the presentation details of your Rails applications. Incoming requests are routed to controllers which, in turn, render view templates. View templates can dynamically create presentable output based on data structures available to them via their associated controllers. It's in this dynamic presentation that Action View really helps to separate the details of presentation from the core business logic of your application.

Rails ships with three different types of view templating systems. The template engine that's used for a particular request is determined by the file extension of the template file being rendered. These three templating systems, and the file extensions that trigger their execution, are: ERb templates (*.rhtml), Builder::XmlMarkup templates (*.rxml), and JavaScriptGenerator or RJS templates (*.rjs).

ERb templates are most commonly used to generate the HTML output of a Rails application; they are also used to generate email messages (though I won't discuss that until Chapter 9). They consist of files ending with the .rhtml file extension. ERb templates contain a mixture of HTML and plain text along with special ERb tags that embed Ruby into the templates, such as <% ruby code %>, <%= string output %>, or <%- ruby code (with whitespace trimmed) -%>. The equals sign denotes a tag that is to output the string result of some Ruby expression. Tags with no equals sign are meant for pure Ruby code and product no output. Here's a simple example of an ERb template that produces a list of book chapters:

<ol>   <% for chapter in @chapters -%>     <li><%= chapter.title %></li>   <% end -%> <ol>

Your templates can also include other subtemplates by passing a :file option to the render method in ERb output tags, such as:

<%= render :file => "shared/project_calendar %>

where project_calendar.rhtml is a file in the shared directory inside of your project's template root (app/views).

This chapter shows you a number of common techniques to make the most out of ERb templates. I'll also show you how to generate dynamic XML using Builder::XmlMarkup templates to generate RSS feeds, for example. Note that although RJS templates are a component of Action View, I'll hold off on discussing them until Chapter 8.




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net