render partial on click

强颜欢笑 提交于 2019-11-30 10:52:14

问题


I would like to call partials on some standard operations. I am using this method for calling the partial:

 %li= link_to 'Delete Event', 'javascript:void(0);', :class => 'alert tiny button', :data => {'reveal-id' => :RevealDelete}
= render 'layouts/reveal_delete', :item => event_display(@event.event), :resource => @event

Then in my partial,

#RevealDelete.reveal-modal


 %a.close-reveal-modal ×
  %h3= "Delete #{item}"
  %p Are you sure you want to delete this?
  =link_to "Delete #{item}", resource, :method => :delete, :remote => :true, :confirm => resource, :class => 'button close-reveal-modal'
  %a.button.alert.close-reveal-modal Cancel

How can I have this has as something like:

link_to 'Delete', '#', :partial => 'layouts/delete', :remote => :true? 

so that I only render that partial when clicked and not when the page loads?


回答1:


You can do that with javascript like:

<%= link_to "Delete", delete_content_path, :remote => true %>

The action in your corresponding controller then will be this:

My Controller:

def delete_content
  respond_to do |format|               
    format.js
  end        
end 

Then you can create the delete_content.js.erb inside your correct directory of the link and there you put the following code:

delete_content.js.erb

$('#div_id').html("<%= render :partial => 'my_partial' %>");

Then in your view:

delete_content.html.erb

<div id = "div_id">
#this div is html div that will render your partial

</div>

Don't forget to put your partial _my_partial.html.erb in the same folder.




回答2:


To add to the accepted answer, I only got it to work after changing the js portion to the following:

$('#div_id').html("<%= escape_javascript(render :partial => 'my_partial') %>");

Without the escape_javascript it was just rendering the partial in the background and not updating the view.




回答3:


on the view do this:

link_to "Delete #{item}", '/model/confirm_deletion', :method => :delete, :remote => true #add the class and extra attributes if neeeded

on your controller

def confirm_deletion
end

and add a view to the confirm_deletion action in js

#RevealDelete.reveal-modal
  %a.close-reveal-modal ×
  %h3= "Delete #{item}"
  %p Are you sure you want to delete this?
  =link_to "Delete #{item}", resource, :method => :delete, :remote => :true, :confirm => resource, :class => 'button close-reveal-modal'
  %a.button.alert.close-reveal-modal Cancel

:javascript
  $(body).append($('#RevealDelete'));

that would make an ajax request to load that custom confirmation dialog, maybe you want to add some wrapper to insert the dialog instead of using body.append



来源:https://stackoverflow.com/questions/15174798/render-partial-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!