Reducing Maintenance with Partials
Learn to maintain our application using Rails partials.
Partial-page templates
Web applications commonly display information about the same application object or objects on multiple pages. A shopping cart might display an order line item on the shopping cart page and again on the order summary page. A blog application might display the contents of an article on the main index page and again at the top of a page soliciting comments. Typically, this would involve copying snippets of code between the different template pages.
Rails, however, eliminates this duplication with the partial-page templates (more frequently called partials). Think of a partial as a kind of subroutine. We invoke it one or more times from within another template, potentially passing it objects to render as parameters. When the partial template finishes rendering, it returns control to the calling template.
Internally, a partial template looks like any other template. Externally, there’s a slight difference. The name of the file containing the template code must start with an underscore character, differentiating the source of partial templates from their more complete brothers and sisters.
For example, the partial to render a blog entry might be stored in the file _article.html.erb
in the normal views directory, app/views/blog
:
Get hands-on with 1200+ tech skills courses.