9.1. Working with Templates

At a certain point, the controller hands over control to the view so that it can build the body of the response based on the appropriate layout, view templates, and partials. This can happen implicitly, when you let Rails process the default template for an action and request format, or explicitly by invoking the render method.

9.1.1. Rendering Templates

This section first reviews how default templates are determined and how it's possible to specify a non-default template to be used for the response to a request. It then takes a look at the available template types and standard engines that Rails bakes-in.

9.1.1.1. Default Templates

The view prominently enters into the picture whenever the response's body depends on a template. As you can imagine, this is the norm for HTML requests because their bodies are typically XHTML documents displayed through a browser. When render isn't called, the default template for a given action is rendered. As mentioned several times, the name of the default template that's going to be used is determined based on the action name and the format requested. If the controller is ExampleController, the view templates for its actions are conventionally stored in app\views\example.

When processing the following action, index.html.erb is rendered by default:

# index.html.erb will be rendered by default
def index
  @books = Book.all
end

If the expected template is missing, a 500 Internal Server Error is raised and a "Template ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.