首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails ActionView 核心服務全解析:模板、佈局、分頁與格式化助手

     編輯:Java 相關知識

ActionView 是 Rails 的視圖層核心,提供模板引擎、佈局機制、分頁元件、格式化助手等服務,讓資料呈現簡潔高效。本文詳細解析四大核心服務並附完整範例。

1. 模板

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。

2. 格式化助手

將 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 -->

3. 分頁

Controller 層使用 paginate,View 層使用 pagination_links。

Controller

def user_list
  @user_pages, @users = paginate(:users, :order_by => 'name')
end

回傳:@user_pages(分頁器)、@users(當頁記錄集合)。

View

<table>
  <tr><th>姓名</th></tr>
  <% for user in @users %>
    <tr><td><%= user.name %></td></tr>
  <% end %>
</table>
<hr>
<%= pagination_links(@user_pages) %>
<hr>

4. 佈局

佈局提供頁面骨架(Header、Footer、Menu),@content_for_layout 為內容插入點。

佈局檔:app/views/layouts/application.rhtml

<html>
<head>
  <title>Form: <%= controller.action_name %></title>
  <%= stylesheet_link_tag 'scaffold' %>
</head>
<body>
  <%= @content_for_layout %>
</body></html>

Controller

def method
  @msg = "測試!"
end

View:app/views/xxx/method.rhtml

<h1><%= @msg %></h1>

最終輸出

<html>
<head><title>Form: method</title>
<link href="/stylesheets/scaffold.css" rel="Stylesheet" /></head>
<body><h1>測試!</h1></body></html>

完整範例:格式化展示

Controller

class SayController < ApplicationController
  def hello
    @time = Time.now
    @rule = "This is a rule"
    @price = 123
  end
end

View

<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>

模板可存取的 Controller 資訊

  1. Instance Variables(@ivar):Controller 設定的實例變數
  2. Controller 存取器:headers、params、request、response、session
  3. 當前 Controller 實例:可呼叫其 public 方法

總結

ActionView 以 ERB 模板、Helper 方法、分頁元件、佈局機制四大支柱,構建「關注點分離」的視圖層。善用 number_to_currency、highlight、pluralize 等 Helper,能大幅減少 View 中的邏輯代碼,保持模板乾淨。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved