ActionView 是 Rails 的視圖層核心,提供模板引擎、佈局機制、分頁元件、格式化助手等服務,讓資料呈現簡潔高效。本文詳細解析四大核心服務並附完整範例。
Rails 模板為 RHTML(ERB) 檔案,副檔名 .rhtml 或 .html.erb。支援兩種標籤:
<%= ... %>:輸出運算結果(回傳最後一行值)<% ... %>:執行 Ruby 程式碼(不輸出)<h1>大家好!</h1>
<p><b>目前日期:</b> <%= Time.now %></p>
<% 5.times do %>
<5>
<% end %>
執行時轉換為:
5.times do
puts "<5>"
end
最佳實踐:View 僅處理呈現邏輯,業務邏輯放入 Model/Controller。
將 Controller 傳遞的資料格式化為使用者友善形式,分三類:
<%= number_to_currency(99.99) %> <!-- $99.99 -->
<%= number_to_percentage(66.6666) %> <!-- 66.667% -->
<%= number_to_percentage(66.6666, :precision => 1) %> <!-- 66.7% -->
<%= number_to_phone(1125551212) %> <!-- 112-555-1212 -->
<%= distance_of_time_in_words(Time.now, Time.local(2006,11,1)) %> <!-- 4 months -->
<%= distance_of_time_in_words(Time.now, Time.now + 40, false) %> <!-- 1 minute -->
<%= excerpt(@str, "you", 8) %> <!-- 擷取含 "you" 前後 8 字 -->
<%= highlight(@str, "love") %> <!-- <strong class="highlight">love</strong> -->
<%= pluralize(2, "person") %> <!-- 2 people -->
Controller 層使用 paginate,View 層使用 pagination_links。
def user_list
@user_pages, @users = paginate(:users, :order_by => 'name')
end
回傳:@user_pages(分頁器)、@users(當頁記錄集合)。
<table>
<tr><th>姓名</th></tr>
<% for user in @users %>
<tr><td><%= user.name %></td></tr>
<% end %>
</table>
<hr>
<%= pagination_links(@user_pages) %>
<hr>
佈局提供頁面骨架(Header、Footer、Menu),@content_for_layout 為內容插入點。
<html>
<head>
<title>Form: <%= controller.action_name %></title>
<%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
<%= @content_for_layout %>
</body></html>
def method
@msg = "測試!"
end
<h1><%= @msg %></h1>
<html>
<head><title>Form: method</title>
<link href="/stylesheets/scaffold.css" rel="Stylesheet" /></head>
<body><h1>測試!</h1></body></html>
class SayController < ApplicationController
def hello
@time = Time.now
@rule = "This is a rule"
@price = 123
end
end
<html><head><title>你好!</title></head><body>
<br>目前報時:<%= @time %>
<br>時間間隔:<%= distance_of_time_in_words(@time, Time.local(2006,10,11)) %>
<br>高亮顯示 rule:<%= highlight(@rule, "rule") %>
<br>價格轉美元:<%= number_to_currency(@price) %>
</body></html>
@ivar):Controller 設定的實例變數headers、params、request、response、sessionActionView 以 ERB 模板、Helper 方法、分頁元件、佈局機制四大支柱,構建「關注點分離」的視圖層。善用 number_to_currency、highlight、pluralize 等 Helper,能大幅減少 View 中的邏輯代碼,保持模板乾淨。