[Rails] Action View Helper
keywords:view helper
TL;DR
# content_tag(<tag>, content, options)
content_tag(:i, nil, class: klass, style: style)
[TOC]
觀念
在 Rails 中,Helper
指的是可以在 Template 中使用的輔助方法,主要用途是可以將資料轉化成輸出用的 HTML 字串。另一個使用 Helper 的理由是可以簡化 Template 中的複雜結構,將 Template 中較為複雜的程式都用 Helper 包裝起來,最好讓 Template 只包含單純的變數以及最簡單的條件邏輯和迴圈,這樣就算是不會程式的網頁設計師,也能夠輕易了解套版甚至修改 Template 樣板。
因為 Helper 預設只能在 Template 中使用,如果想在 rails console
中呼叫,必須加上關鍵字 helper
,例如 helper.link_to
。
另外,雖然機會不多,如果真的要在 Rails Controller 或 Model 程式中呼叫 Helper,則可以加上 ApplicationController.helpers
前置詞。
Action View Overview @ RailsGuides Overview of helpers provide by action view @ RailsGuides in Action View Overview
自訂 Helper(Customer View Helper)
除了使用 Rails 內建的 Helper,我們可以建立自定的 Helper(不要把邏輯規則寫在 view 中),只需要將方法定義在 app/helpers/
目錄下的任意一個檔案就可以了(因為所有的 View Helper 都可以被 Rails 載入)。
在產生 Controller 的同時,Rails 就會自動產生一個同名的 Helper 檔案,照慣例該 Controller 下的 Template 所用的 Helper,就放在該檔案下。如果是全站使用的 Helper,則會放在 app/helpers/application_helper_rb。
- Custom View Helpers in Rails 5 @ RubyPlus
- create custom html helpers in ruby on rails @ StackOverflow
使用客制化的 Helper
在 View 中使用
在 View 中,可以直接使用該 helper。
在 Controller 中使用
如果要在 Controller 中使用,則可以用 helpers.helper_name()
。
helpers.number_to_currency(line_item.ticket.unit_price, locale: :'zh-TW', precision: 0)
- Use a Helper inside a Controller @ StackOverflow
在 Mailer 中使用
在 Mailer 中使用,可以加上 add_template_helper [HelperName]
class OrderMailer < ApplicationMailer
add_template_helper XeatHelper
# default from: 'info@passer.cc'
layout 'order_mailer'
def order_email(order, subject)
mail(to: order.user.email, subject: subject)
end
end
HTML 結構相關
color_field
date_field
email_field
month_field
number_field
url_field
range_field
search_field
content_tag # 產生有內容的 HTML標籤
tag # 產生 HTML 標籤
# 放在 <head></head> 裡面
javascript_include_tag # 產生 link:js
stylesheet_link_tag # 產生 script:src
csrf_meta_tags # 避免 cross site request forgery attack(CSRF)
auto_discovery_link_tag
favicon_link_tag
video_tag
audio_tag
link_to # 文字超連結(預設是用 GET)
mail_to # E-mail
button_to # 按鈕連結(預設是用 POST)
current_page?(url) # 是否目前是url這個頁面
格式化 Format 相關
simple_format # 將一些HTML格式簡化
truncate # 擷取前幾個字元
strip_tags # 把 HTML 的標籤拿掉
strip_links # 移除 HTML 連結標籤
sanitize # 將 HTML 中不合法的 tag 或 attribute 移除
時間相關(DateHelper)
keywords: date_select
, datetime_select
, select_date
, select_datetime
, select_day
, select_hour
, select_minute
, select_month
, select_second
, select_time
, select_year
, time_ago_in_words
, time_select
, distance_of_time_in_words
,
DateHelp @ RailsGuides in Action View Overview
除錯相關(DebugHelper)
keywords: debug
在 View 中使用 debug
關鍵字,可以讓物件變得以容易閱讀的方式輸出於網頁上:
# View Helper
my_hash = { 'first' => 1, 'second' => 'two', 'third' => [1,2,3] }
debug(my_hash)
數字相關
number_with_delimiter # 將數字加上每三位加上",",例如,12,345,678
number_with_precision # 四捨五入到小數第幾位
sprintf # 用來格式化數值
number_to_currency # 將數值轉為貨幣金額
表單相關(FormHelper)
筆記在其他頁中
image 相關 helper
keywords: image_path
, image_url
, image_tag
image_tag('avatar.jpg') # 取得放在 assets/images 中某圖檔的相對路徑,並建立 <img> 標籤
image_path('avatar.jpg') # 取得放在 assets/images 中某圖檔的相對路徑
image_url('avatar.jpg') # 取得放在 assets/images 中某圖檔的相對路徑
圖片預設要放在
app/assets/images
image_tag:
image_tag("icon.png") # => <img src="/assets/icon.png" alt="Icon" />
image_tag "icons/delete.gif"
# 使用 Hash 給予設定
image_tag "icons/delete.gif", { height: 45 }
image_tag "home.gif", size: "50x20"
# 給與圖片 class, alt, id
image_tag "home.gif", alt: "Go Home", id: "HomeImage", class: "nav_bar"
JavaScript 相關 helper
keywords:javascript_include_tag
, javascript_url
, javascript_path
javascript_include_tag
:載入在app/assets/javascripts
中的 JS 檔javascript_url
:取得該 JS 檔的相對路徑javascript_path
:取得該 JS 檔的絕對路徑
JS 檔案預設放在
app/assets/javascripts
javascript_include_tag
自動載入 js 檔:
# 載入 ./assets/ 中特定一支 js 檔
javascript_include_tag "common" # => <script src="/assets/common.js"></script>
javascript_include_tag "http://example.com/main.js"
# 載入 ./assets/ 中多支 js 檔
javascript_include_tag "main", "columns"
javascript_include_tag "main", "/photos/columns"
# 載入 ./assets/ 中所有 js 檔
javascript_include_tag :all
若要將所有的 JS 檔快取成一支檔案,可以透過設定 ActionController::Base.perform_caching
成 True 達到,預設 production mode 是 true;developemnt mode 是 false:
# 快取
javascript_include_tag :all, cache: true # => <script src="javascripts/all.js"></script>
javascript_path, javascript_url
javascript_path "common" # 相對路徑 => /assets/common.js
javascript_url "common" # 絕對路徑 => http://www.example.com/assets/common.js
stylesheet 相關 helper
keywords: stylesheet_link_tag
, stylesheet_path
, stylesheet_url
預設檔案放在 ./assets/stylesheets/
資料夾中;此外預設會產生 media="screen" rel="stylesheet"
,可以透過:media
或 :rel
選項覆蓋預設值。
stylesheet_link_tag
# 載入 ./assets/ 中特定一支 css 檔
stylesheet_link_tag "application" # => <link href="/assets/application.css" media="screen" rel="stylesheet" />
# 載入 ./assets/ 中多支 css 檔
stylesheet_link_tag "main", "columns"
# 如果要載入所有的 css 樣式檔
stylesheet_link_tag :all
若要將所有的 CSS 檔快取成一支檔案,可以透過設定 ActionController::Base.perform_caching
成 True 達到,預設 production mode 是 true;developemnt mode 是 false
stylesheet_link_tag :all, cache: true
# => <link href="/assets/all.css" media="screen" rel="stylesheet" />
stylesheet_path, stylesheet_url
stylesheet_path "application" # 相對路徑 => /assets/application.css
stylesheet_url "application" # 絕對路徑 => http://www.example.com/assets/application.css
其他
keywords: link_to
link_to
keywords: data-method
, data-remote
, data-params
<%= link_to "Add to cart", cart_path, data: { method: :post, remote: true, params: { product_id: product.id }.to_param } %>
參考資料
- ActionView Helpers @ Rails API
- ActionView Helpers @ Rails 實戰聖經 by ihower
- Form Helper @ Rails API
- Form Builder @ Rails API