少於 1 分鐘閱讀

基本用法

例如:app/view/comments/_comment.html.erb

其他 template 要引用此 partial:

<%= render :partial => "comments/comment" %>

簡略寫法:

<%= render "comments/comment" %>

帶入參數

<%= render :partial => "comments/comment", :locals => { :a => 1, :b => 2 } %>

簡略寫法:

<%= render "comments/comment", :a => 1, :b => 2 %>

Collection用法

例如:app/view/comments/_comment.html.erb

在post的template中要放入相關的comments(partial):

原寫法:

<!-- [path] app/view/posts/view.html.erb -->
<% @comments.each do |comment| %>
 <%= render :partial => "comment", :locals => { :comment => comment } %>
<% end %>

可改寫為:

<!-- [path] app/view/posts/view.html.erb -->
<%= render :partial => "comment", :collection => @comments, :as => :comment %>

若檔案名稱剛好與model相同,更省略的寫法:

<!-- [path] app/view/posts/view.html.erb -->
<%= render @comments %>

PS.在此Collection的partail內可使用xxx_counter當作此loop的counter

<!-- [path] app/view/comments/_comment.html.erb -->
<%= comment_counter %> ## 0 1 2 ...

留言