JT's Blog

Do the right things and do the things right.

Rails Partials

| Comments

用來簡化 View 複雜的程式邏輯

把細節的部份拆出去,更容易理解 View 的全局

檔名需要以底線開頭,但呼叫時不需加上底線

Action View Partials 用來 render sub templates

Syntax

1
<%= render partial: sub_template_name, *options %>
  • render is a shorthand for render partial:
  • 單使用 render, Rails 就不會處理後續的 options
  • 如果要使用 options 就要改成 render partial:

Default Case

使用 render 產生 partial

1
2
3
4
<%= render partial: "account" %>

# equivalent to
<%= render "account" %>

sub template name equivalent to variable name

1
2
3
4
<%= render partial: "accounts/account", locals: { account: @account} %>

# equivalent to
<%= render @account %>

只有單一個 locals

1
2
3
4
<%= render partial: "account", locals: { account: @buyer } %>

# equivalent to
<%= render "account", account: @buyer %>

都同名可簡化 collection

1
2
3
4
<%= render partial: "posts/post", collection: @posts %>

# equivalent to
<%= render @posts %>

Options

locals

傳遞資料

1
<%= render partial: "user", locals: { user: @user, order: @order } %>

collection

使用 for-each render 逐一產生 partial

1
2
3
4
5
6
7
8
9
10
11
12
# index.html.erb
<%= render partial: "product", collection: @products %>

# _product.html.erb
Product Name: <%= product.name %>

# short-hand
<%= @products %>

# if collection is empty, render will return nil,
# should simple to provide alternative message.
<%= render(@products) || "Empty Products" %>

layout

指定 render layout,使用時,需要加上 partial: 才能執行

1
<%= render partial: "user", locals: { user: @user, order: @order }, layout: 'editor' %>

進階 Layout - layout + yield

動機

把共用的 view 寫在 layout ,然後客製(變動)的內容寫在partial

開發

1.寫一個 layout 專用的 partial view,並把需要客製的部份加上 yield

1
2
3
4
5
<%# app/views/users/_editor.html.haml %>
#editor
  %h1 always the same headline
  %h3 always the same description
  = yield

2.寫客製的 partial view

1
2
3
<%# app/views/users/_user.html.haml %>
= "Deadline: #{user.deadline}"
= "Name: #{user.name}"

3.render 設定 partial and layout,就可以把 partial 的內容套在 layout 的 yield 區塊內

1
2
<%# app/views/users/index.html.haml %>
<%= render partial: "user", layout: "editor", locals: { user: @user } %>

如果不用 yield,可以使用 block 表現

1
2
3
<%= render layout: "editor", locals: { user: @user } do %>
  <%= do_something %>
<% end %>

實際應用:把預覽圖片跟上傳圖片的功能提取出來,並且可個別設定內部要呈現的內容,例如:產品說明、大頭照說明等

Helper + Partial

這次要把partial 放進 helper 內

1.一樣建立 partial,把要執行客製的部分使用 capture(&block) 表示

1
2
3
4
5
<%# app/views/users/_editor.html.haml %>
#editor
  %h1 always the same headline
  %h3 always the same description
  = capture(&block)

2.在helper 寫method 呼叫 render partial:

1
2
3
4
5
6
7
# application_helper.rb
def modal_for(heading, &block)
  render(
    partial: 'shared/modal',
    locals: { heading: heading, block: block }
  )
end

3.在view 使用helper

1
2
3
<%= modal_for('My Title') do |t| %>
  # print dynamic things here
<% end %>

實際應用:把預覽圖片跟上傳圖片的功能提取出來,並且可個別設定內部要呈現的內容,例如:產品說明、大頭照說明等

Reference

Comments