Views (see UnderstandingMVC for an overview) are the user interface of a web application.
In Rails, the view is rendered using RHTML or RXML. RHTML is HTML with embedded Ruby code and RXML is Ruby-generated XML code.
The controller chooses which view to render, and makes available the data that the view needs. The view will typically contain links to other actions, which means a controller does some processing and renders another view, perhaps the same view. In this way the user moves from view to view throughout the application, or perhaps seeing the same view with different data.
The view uses instance variables set by the controller to access the data it needs to render a useful display. For example, a user’s details might be shown in a view like this:
<html>
<body>
User <%= @user.name %>:
<ul>
<li>Age: <%= @user.age %></li>
<li>Interests: <%= @user.interests.join(', ') %></li>
<li>Occupation: <%= @user.occupation %></li>
</ul>
</body>
</html>
That @user is a Ruby instance variable which the controller set. In a typical simple Rails application, many or most of these instance variables will be model objects, thus tightly integrating the model, view, and controller. However, the instance variables can contain any data, and it is the model’s job to provide the correct data for the view.
The view has a name: its filename. The tight relationship between views and controllers is explored in UnderstandingControllers and UnderstandingRailsMVC.
See also:
Q: How does a controller specifiy a view other than the default view?
A: Views are related to actions, not controllers per se. The action UserController#preferences will by default render the file views/user/preferences.rhtml. If you want it to render views/user/index.rhtml instead, call render_action 'index' inside the action. You can also render a named file or a partial; see the API docs for details.
Q: So render_action does not actually refer to another action, and the value passed is the name of a view, not an action?
Q: What exactly does
<%= ... %> and <% ... %> mean? How do they differ?
A: By using
<%= ... %> you send the results of what happend in the code-block back to the requesting client (without using any kind of ‘print’-command), while <% ... %> just contains some Ruby-Code to be executed – for example if-conditions… .
Q: Can you include views in views (subviews)? How?
A:: Yes, this is done by rendering partials. See ActionView::Partials for more information.
Q: What is the context/scope while inside an rhtml block?
Q: What variables are available in the rhtml?
Q: How is the rhtml file to be displayed selected?
Q: What does
<%- ... -%> do? How does it differ from <% ... %>?
This is primarily about the addition of line feeds between generated html elements. With the ‘-’ in place there is much reduced white space in the output, plus fewer bytes sent to deliver a web page…
category: Understanding