web-dev-qa-db-ja.com

link_toを使用してbootstrap modalを追加して、リンクコンテンツをmodalで開く方法は?

bootstrapモーダル http://Twitter.github.com/bootstrap/javascript.html#modals をRailsリンクをモーダルで開く

<%= link_to page_path, target: '_blank' %>

しかし、どういうわけか機能していません。標準のトグルコードは-

<a data-toggle="modal" href="#myModal" class="btn">Launch demo modal</a>

しかし、私はそれをRailsのlink_toに適用する方法がわからない、何か助けがありますか?

ありがとう

25
iCyborg

以下は、非表示状態のページにモーダルをプリロードする場合のコードです

<%= 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>

そして、ajaxを介してモーダルをロードしたい場合は、このようなことを行うことができます

<%= 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>

posts/new.js.erbに含めるもの

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

すべてのモーダルボディにnique idまたはクラスがあることを確認してください。

モーダルフォームを使用して新しい投稿を作成する場合、コントローラーコードと_form.html.erbが配置されている

38
benchwarmer

Railsにdata属性を追加するより良い方法があります。同じ結果を得るには、このようなことを行うことができます。

<%= link_to 'Click Here', "#", data: {toggle: "modal", target: "#modal"} %>
18
kobaltz