5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

twitter-bootstrap-railsとSlimの組み合わせとModalHelperでハマった問題

Posted at

twitter-bootstrap-railsは標準でSlimにも対応しています。
その中でModalHelperを使った際に発生した問題があったので、対応法について。


公式にあるモーダルのサンプルをそのまま使おうとした際に

sample.html
    <!-- Button to trigger modal -->
    <a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
     
    <!-- Modal -->
    <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
    <p>One fine body…</p>
    </div>
    <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
    </div>
    </div>

をSlimとModalHelperで記述すると、以下のようになります。

sample1.slim
= modal_toggle({:href=>"#myModal", :role=>"button" }) do "ボタン" end

= modal_dialog({:class=>"modal hide fade", :id=>"myModal",:tabindex=>"-1", "role"=>"dialog", "aria-labelledby"=>"myModalLabel", "aria-hidden"=>"true"}) do
  = modal_header() do
    h3 id="myModalLabel" Modal header
  = modal_body() do
    p One fine body…
  = modal_footer() do
    = modal_cancel_button("Close", {"data-dismiss"=>"modal", "aria-hidden"=>"true"})

これだと、初期画面表示時にモーダルが表示されてしまいます。原因は

modal_helper.rb
  def modal_dialog(options = {}, escape = true, &block)
    default_options = {:class => "bootstrap-modal modal"}
    content_tag :div, nil, options.merge(default_options), escape, &block
  end

となっていて、classの内容がdefault_optionsで上書きされるためです。
なので、イケてないですが、下記のようにすればうまく動きました。

sample2.slim
= modal_toggle({:href=>"#myModal", :role=>"button" }) do "ボタン" end

- default_options = {:class=>"modal hide fade", :id=>"myModal",:tabindex=>"-1", "role"=>"dialog", "aria-labelledby"=>"myModalLabel", "aria-hidden"=>"true"}
= content_tag :div, nil, default_options, true do
  = modal_header() do
    h3 id="myModalLabel" Modal header
  = modal_body() do
    p One fine body…
  = modal_footer() do
    = modal_cancel_button("Close", {"data-dismiss"=>"modal", "aria-hidden"=>"true"})
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?