How to add bootstrap modal with link_to so the link content open in modal ?

后端 未结 3 635
死守一世寂寞
死守一世寂寞 2020-12-01 04:09

I am trying to use bootstrap modal http://twitter.github.com/bootstrap/javascript.html#modals on a rails link to open that link in the modal

<%= link_to          


        
相关标签:
3条回答
  • 2020-12-01 04:17

    Below is the code if you want to preload the modal on the page in hidden state

    <%= link_to "Open modal", "#my-modal", :class => "btn", "data-toggle" => "modal" %>
    <div class="modal hide fade" id="my-modal" title="My modal">
      <div class="modal-header">
        <button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>
        <h3 id="myModalLabel">Modal header</h3>
      </div>
      <div class="modal-body">
        Modal Body
      </div>
      <div class="modal-footer">
        <button aria-hidden="true" class="btn" data-dismiss="modal">Close</button>
      </div>
    </div>
    

    And if you want to load the modal through ajax then you can do something like this

    <%= link_to "Open modal", new_post_path, :class => "btn", :remote => true, "data-toggle" => "modal", "data-target" => "my-modal" %>
    <div class="modal hide fade" id="my-modal" title="My modal">
      <div class="modal-header">
        <button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>
        <h3 id="myModalLabel">New Post</h3>
      </div>
      <div class="modal-body a-unique-class">
        New Post Body
      </div>
      <div class="modal-footer">
        <button aria-hidden="true" class="btn" data-dismiss="modal">Close</button>
      </div>
    </div>
    

    In posts/new.js.erb you would include

    $(".a-unique-class").html('<%= j render "posts/_form" %>')
    

    Make sure that you have a unique id or class for every modal body.

    Assuming you want to create a new post using modal form, the controller code and _form.html.erb is in place

    0 讨论(0)
  • There is a syntax error in benchwarmer's answer above.

    try this instead:

    $(".a-unique-class").html('<%= j render "posts/form" %>')
    
    0 讨论(0)
  • 2020-12-01 04:38

    There is a prettier way to add data attributes in Rails. You can do something like this to get the same results.

    <%= link_to 'Click Here', "#", data: {toggle: "modal", target: "#modal"} %>
    
    0 讨论(0)
提交回复
热议问题