Easy Rails Live Preview
Posted on September 18, 2007 at 04:29 PM
So you are adding comments to your app and you would like to provide live preview functionality. There is a simple and effective way to do it.
Lets start by creating a new comment form:
New Comment
<-% form_for(@comment) do |f| %>
<-%= render :partial => 'form', :locals => {:f => f} %>
<-%= f.submit "Save Comment" %>
<-% end %>
Now we need to write an observer to watch our form for changes. It’s important that your form has an unique id, such as “new_comment”.
<-%= observe_form "new_comment",
:frequency => 2,
:update => "live_preview",
:complete => "Element.show('live_preview')",
:url => { :controller => 'comments', :action => 'preview' } %>
Note in the observe_form method above you tell it update “live-preview” every 2 seconds. Create a div with an id of live_preview and set it’s display property to none.
Next create a preview method in your comments controller
def preview render :layout => false end
The next step is to create a view that will be used to display your live preview data. I called my view preview.html.erb.
Your Comment: <-%= params[:comment][:body] %>
You will also need to add a route if you are using rails edge for the preview action:
map.preview 'comment_preview', :controller => 'comments', :action => 'preview'
That should be enough to setup a simple live preview.
Enjoy!
Comments
There are 0 comments on this post. Post yours →
Post a comment
Required fields in bold.