Live Preview [Rails Recipes]

用prototype完成用户预览功能。

在layout里面加载prototype.js
<%= include_javascript_tag "prototype" %>


用一个日记的例子,定义一个model class Entry, 在里面定义title, body.
class Entry
  attr_accessor :title, :body
end


还有一个DiaryController:
def new
  @entry = Entry.new
end


定义这个action的view
<% form_tag(:action => "save",:id => "entry-form") do %>
<%= text_field :entry, :title %><br />
<%= text_area :entry, :body %><br />
<%= submit_tag "Save" %>
<% end %>
<%= observe_form "entry-form",
                 :frequency => 1,
                 :update => "live-preview",
                 :complete => "Element.show(' live-preview' )",
                 :url => { :action => "preview" } %>
<div id="live-preview" style="display: none; border: 1px solid"></div>


完成preview action
def preview
  render :layout => false
end


The layout
<h2>Diary entry preview</h2>
<h3><%= params[:entry][:title] %></h3>
<%= textilize params[:entry][:body] %>


textilize need RedCloth

要在contoller里面处理一下回车和<br>才能正常显示 :)

你可能感兴趣的:(JavaScript,prototype,Ruby,Rails)