Partial templates help you reuse small pieces of HTML code in different places. This keeps your views clean and avoids repeating the same code.
0
0
Partial templates in Ruby on Rails
Introduction
You want to show the same header or footer on many pages.
You have a list of items and want to render each item the same way.
You want to split a big view into smaller, easier parts.
You want to reuse a form in multiple places.
You want to keep your code organized and easier to maintain.
Syntax
Ruby on Rails
<%= render 'partial_name' %>The partial file name starts with an underscore, like
_partial_name.html.erb.You can pass variables to partials using
locals, for example: <%= render 'partial_name', locals: { user: @user } %>.Examples
Renders the
_header.html.erb partial in the current view.Ruby on Rails
<%= render 'header' %>Renders the
_user.html.erb partial and passes the @user variable as user.Ruby on Rails
<%= render partial: 'user', locals: { user: @user } %>Renders the
_article.html.erb partial for each article in the @articles collection.Ruby on Rails
<%= render @articles %>
Sample Program
This example shows a list of articles. The index.html.erb view renders the _article.html.erb partial for each article in @articles. Each partial shows the article's title and content.
Ruby on Rails
<!-- app/views/articles/index.html.erb --> <h1>Articles</h1> <%= render @articles %> <!-- app/views/articles/_article.html.erb --> <div class="article"> <h2><%= article.title %></h2> <p><%= article.content %></p> </div>
OutputSuccess
Important Notes
Partial names always start with an underscore but you omit the underscore when rendering.
Passing variables with locals helps make partials flexible and reusable.
Rendering collections automatically loops over each item and renders the partial with the item as a local variable.
Summary
Partial templates let you reuse small view pieces easily.
Use render 'partial_name' to include a partial.
You can pass data to partials with locals or render collections directly.