The file wrapping every view

Free preview 2 min to read

Every page's missing half

partners.html.erb, opened in the last course, never mentions an <html> tag, a <head>, a navbar or a footer. Visit /partners in a browser and all of that is there, the same header and footer every other page shares. That missing half lives in one file, app/views/layouts/application.html.erb, the wrapper every view in this app renders inside.

One wrapper, every view

application.html.erb
+-----------------------------+
| <html><head>...</head>       |
| <body>                       |
|   <navbar>                   |
|   +-----------------------+  |
|   |  partners.html.erb    |  |
|   |  (or any other view)  |  |
|   +-----------------------+  |
|   <footer>                   |
| </body></html>               |
+-----------------------------+

Whatever view an action renders, partners.html.erb, the example articles/show.html.erb or any other, slots into the same outer shell. No view repeats the <html> tag, stylesheet links or navbar; the layout supplies them once for every page.

The one piece left unexplained

Lesson 6 of the last course quoted one line from this file, <%= content_for(:title).presence || "Newbie on Rails" %>, without explaining how a view's content ends up inside the wrapper. That's this course's subject: yield, the word that inserts a view into the layout.

Where this course goes

  • Lesson 2 covers bare yield, inserting the current view's rendered content.
  • Lesson 3 covers named yield(:name) and content_for(:name), optional slots a view can choose to fill.
  • Lesson 4 compares this yield with the one from Ruby blocks (do..end).
  • Lesson 5 reads this project's layout file.
  • Lesson 6 watches a real view fill one of those slots.
  • Lesson 7 puts it together and names what comes next.
Lesson 1 of 7 · free

Keep going with lesson 2

Bare yield: inserting the current view

Explains how bare yield inserts the current action's rendered view inside main, with everything else shared.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...