Reusable Components

Learn about partials as reusable components of our Rails application.

Partials as reusable components

There is often a need to extract common markup for reuse, and partials are the best way to do that. We like to think of reusable markup as components because the markup is rendering data, and it’s this combination of dynamic input and rendering that feels like more than just copying HTML elements around. To make partials effective and sustainable at managing reusable components, there are two guidelines that help:

  • Do not use partials for any purpose other than reusable components.
  • Partials should use locals for parameters, not instance variables.

Before we get into these guidelines, we want to talk about why we are not recommending layouts and helpers for this purpose.

Don’t use layouts for reusable components

Layouts are most useful for global cross-cutting concerns like the inclusion of stylesheets or a site-wide navigation bar. Although Rails allows us to use different layouts when needed, it’s hard to nest layouts or compose them in a flexible way.

Apps often end up with an application layout that has a lot of conditional content in it using yield and content_for, and as a mechanism ...