像蛙眼等有时候需要给用户提供预览查看,今天我们就来看看利用Rails和Prototype快捷的提供Live Preview功能。
1,在layout里加入prototype.js
如app/views/layouts/standard.rhtml:
[code]
<html>
<head>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<%= yield %>
</body>
</html>
[/code]
2,定义Entry类
如app/models/entry.rb:
[code]
class Entry
attr_accessor :title, :body
end
[/code]
我们的demo中的模型没有继承ActiveRecord::Base类,只是简单的提供两个可访问的字段
3,定义controller
如app/controllers/diary_controller.rb:
[code]
class DiaryController < ApplicationController
layout 'standard'
def new
@entry = Entry.new
end
def preview
render :layout => false
end
end
[/code]
4,定义rhtml模板
app/views/diary/new.rhtml:
[code]
<%= start_form_tag({:action => "save"}, :id => "entry-form")%>
Title:<%= text_field :entry, :title %><br/>
Content:<%= text_field :entry, :body %><br/>
<%= submit_tag "Save" %>
<%= end_form_tag %>
<%= 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>
[/code]
app/views/diary/preview.rhtml:
[code]
<h2>Diary entry preview</h2>
<h3><%= params[:entry][:title]%></h3>
<%= textilize params[:entry][:body] %>
[/code]
5,打完收工
访问[url]http://localhost:3000/diary/new[/url]即可看到Live Preview效果
1,在layout里加入prototype.js
如app/views/layouts/standard.rhtml:
[code]
<html>
<head>
<%= javascript_include_tag "prototype" %>
</head>
<body>
<%= yield %>
</body>
</html>
[/code]
2,定义Entry类
如app/models/entry.rb:
[code]
class Entry
attr_accessor :title, :body
end
[/code]
我们的demo中的模型没有继承ActiveRecord::Base类,只是简单的提供两个可访问的字段
3,定义controller
如app/controllers/diary_controller.rb:
[code]
class DiaryController < ApplicationController
layout 'standard'
def new
@entry = Entry.new
end
def preview
render :layout => false
end
end
[/code]
4,定义rhtml模板
app/views/diary/new.rhtml:
[code]
<%= start_form_tag({:action => "save"}, :id => "entry-form")%>
Title:<%= text_field :entry, :title %><br/>
Content:<%= text_field :entry, :body %><br/>
<%= submit_tag "Save" %>
<%= end_form_tag %>
<%= 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>
[/code]
app/views/diary/preview.rhtml:
[code]
<h2>Diary entry preview</h2>
<h3><%= params[:entry][:title]%></h3>
<%= textilize params[:entry][:body] %>
[/code]
5,打完收工
访问[url]http://localhost:3000/diary/new[/url]即可看到Live Preview效果