A "partial template" is a View file that can be used in common on multiple pages. By combining the code that is duplicated in multiple files into one file, you only need to modify it in one place at the time of modification, and the code description is reduced and readability is improved.
The procedure is roughly like this.
As it is, it is a task to find duplicates.
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
Cut out the common part and paste it into the file. Basically, partial template files use local variables (those without @). This is because if you use an instance variable (the one with @) in the partial template file, when you change the name or behavior of the instance variable 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>
The way to write when calling is as follows. When calling, omit the underscore of the partial template.
<%= render [Specifying a partial template file], [Local variables]:[Value to pass] %>
app/views/books/index.html.erb
<%= render 'books/newform', book: @book %>
Recommended Posts