如何在单个模态中加载任何部分

时间:2014-03-22 18:32:14

标签: ruby-on-rails twitter-bootstrap-3

我正在试图在同一个引导模态代码中加载一个符号UP部分和一个符号IN部分,以保持干燥。

目前的情况怎么可能呢?

<%= link_to "Sign in", :sign_in, id: "signin",  "data-toggle" => "modal", "data-target" => "#sign-in" %>

模态部分

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Sign In</h4>
      </div>
      <div class="modal-body">
        <%= render "sessions/new" %>
      </div>
    </div>
  </div>
</div>

新会话部分

<div class="row">
  <div class="span6 offset3">
    <%= form_for(:session, url: sessions_path) do |f| %>

        <%= f.label :email %>
        <%= f.text_field :email %>

        <%= f.label :password %>
        <%= f.password_field :password %>

        <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
    <% end %>

    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

我会渲染两个部分并使用javascript来显示/隐藏正确的部分。请确保在注册部分中使用最外层元素中的类signup,然后在注册部分正下方的渲染中渲染

<%= link_to "Sign in", :sign_in, id: "signin",  "data-toggle" => "modal", "data-target" => "#sign-in" %>

<%= link_to "Sign in", :sign_in, id: "signup",  "data-toggle" => "modal", "data-target" => "#sign-in" %>

<div class="row signin">
  <div class="span6 offset3">
    <%= form_for(:session, url: sessions_path) do |f| %>

        <%= f.label :email %>
        <%= f.text_field :email %>

        <%= f.label :password %>
        <%= f.password_field :password %>

        <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
    <% end %>

    <p>New user? <%= link_to "Sign up now!", signup_path %></p>
  </div>
</div>

的Javascript

$(document).ready(function() {
  $("#signin").click(function() {
    $(".modal .signup").hide();
    $(".modal .signin").show();
  });

  $("#signup").click(function() {
    $(".modal .signin").hide();
    $(".modal .signup").show();
  });
});

另一种方式

另一种方法是使用ajax将部分加载到模态的主体中。你需要一个控制器操作,只需渲染一个部分并且layout false,所以你不会得到多余的布局元素。

如果你没有很多,你不需要把它变成一个新的控制器,但我只是在这里做了

的Javascript

$(document).ready(function() {
  $("#signup").click(function() {
    setModal("modals/signup");
  });

  $("#signin").click(function() {
    setModal("modals/signin");
  });
});

// Doesn't have to be in a function, but it's better to keep it dry.
// Could also add more configuration (like the selector it uses)
function setModal(url) {
  $.get(url, function(data) {
    $("#myModal .modal-body").html(data);
  });
 }

控制器

class ModalsController < ApplicationController
  def signin
    render partial: "sessions/new", layout: false
  end

  def signup
    render partial: "registrations/new", layout: false
  end
end

路线

get "modals/signin", to: "modals#signin"
get "modals/signup", to: "modals#signup"