Blog / How to use Partials in Rails

How to use Partials in Rails

Blair Rorani

February 23, 2021

If you want to keep your code simple and/or reuse a block of code in multiple files, then you can store that code in an html.erb file called a partial.

Create partial 🧩

  1. Go to app > views.
  2. Create a folder called shared.
  3. Create a file to store your code in and name it using the syntax: _[partial].html.erb Insert partial ⬇️

In the file where you want to include the code from a partial, insert the tag
<%= render partial "shared/[partial]%>

View page 👀

You’ll see your page with the code from the partial included.

P.S. You might enjoy following me on Twitter.


Comments
Loading...

Want to stay up-to-date with Ruby on Rails?

Join 52,887+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.