[Ruby] [rails] How to create partial template

1 minute read

What is a partial template?

A “partial template” is a View file that can be shared by multiple pages. By collecting the code that is duplicated in multiple files in one file, you only have to modify it in one place at the time of modification, and the code description is reduced and the readability is improved.

The procedure is roughly like this.

  1. Find a part that can be shared
  2. Create a partial template file
  3. Describe the common part in the partial template file
  4. Call the partial template file

1. Find the part that can be shared

It is as it is, but it is a work to find the overlapping part.

2. Create a partial template file

An erb file with an underscore (_) at the beginning of the file name is recognized as a partial template file. This time we will look at the posting function as a partial template. app/views/books/_newform.html.erb

3. Describe the common part in the partial template file

Cut out the common part and paste it in the file. Basically, local variables (those without @) are used in partial template files. This is because if you use an instance variable (the one with @) in the partial template file, when you change the instance variable name or behavior on the controller side, you also have to change the partial template side.

app/views/books/_newform.html.erb


<%= form_for(book) do |f| %>
<div class="field row">
<%= f.label :title %><br>
<%= f.text_field :title, class: "col-xs-3 book_title" %>
</div>
<p></p>

<div class="field row">
<%= f.label :body %><br>
<%= f.text_area :body, class: "col-xs-3 book_body" %>
</div>

<div class="actions row">
<%= f.submit class: "btn btn-primary col-xs-3" %>
</div>
<% end %>
</div>

4. Call the partial template file

The way to write when calling is as follows. When calling, omit the underscore in the partial template.

<%= render [Specify partial template file], [Local variable]:[Pass value] %>

app/views/books/index.html.erb


<%= render'books/newform', book: @book %>