Rails RJS Templates 初體驗

RJS templates 是 Rails 1.1 中的一種新 template,它的開發者 Sam Stephenson 也是 Prototype.js 的作者。不像一般 template 產生 HTML 或 XML,RJS templates 產生 Javascript (based on prototype) code 傳給瀏覽器執行,你可以在 template 中一次修改頁面多個地方,而所有 template 語法皆是用 Ruby 來寫。

要學RJS template,目前最好的文件應該就是這份 Cody Fauser 所寫的 RJS Templates for Rails 了,直接線上買PDF版(也只有PDF版),而且作者會更新,我手上的是 9/26。另外 slash7 提供了一份漂亮圖例 RJS Demystified With Pretty Colors!。RubyInside 則有整理了一份 16 RJS Resources and Tutorials for Rails Programmers

以下是一個簡單的Ajax範例,需要寫的程式碼很少,而且重點是不需要寫 JavaScript。

首先建立 Controller 及兩個 action index跟note
ruby script/generate controller Rjs1

#/app/controllers/rjs1_controller.rb
class Rjs1Controller < ApplicationController
 def index
 end
 def note
 @note = params[:note]
 end
end

這是搭配 action index 的 HTML template,有一個Ajax的表單輸入框。以下省略 html 的前後,記得head裡要加 < %= javascript_include_tag :defaults %> 使用 prototype.js。

#/app/views/rjs1/index.rhtml
< %= form_remote_tag :url => { :action =>’note’ }, :html => {:id=>’note-form’ } %>
< %= text_field_tag ‘note’,nil,:size => 40 %>
< %= submit_tag ‘submit’ %>
< %= end_form_tag %>

重頭戲,這是 action note 用的 RJS template,第一行在 id=”notes” 的元素裡面插入 partial template 區塊,第二行加特效,第三行重設表單。

#/app/views/rjs1/note.rjs
page.insert_html :bottom, ‘notes’, :partial =>’note’
page.visual_effect :highlight, ‘note’
page.form.reset ‘note-form’ 

這是上述用到的 partial template,這裡的 note 變數透過 Controller 中的 @note 傳進來使用。

#/app/views/rjs1/_note.rhtml
< %= Time.now.to_s %>
< %=h note %>

仔細想想RJS templates的概念,你會覺得非常有意思,實在是融合的非常漂亮。

參與討論

2 則留言

  1. 自動引用通知: -TMA-1- » links for 2006-10-30

發佈留言

發表迴響