【问题标题】:How can I render the show action inside of the Bootstrap 4 Modal?如何在 Bootstrap 4 Modal 中渲染显示动作?
【发布时间】:2016-04-10 03:21:04
【问题描述】:

我正在使用可点击图像链接的显示操作填充 bootstrap 4 模式。我目前正在使用 Carrierwave 上传图像。此时,当我单击图像时,仅显示模态叠加层。里面有内容的模态容器根本不显示。

用户/Show.html.erb

<div class= "container">
<div class="username">@user.username</div>
<div class="posts_container_pos">
        <hr style="border: 2px solid #515558;">
          <%= render 'posts/posts', post_items: @user.posts %>
      </div>
</div>

帖子/_Posts.html.erb

    <div class"container-fluid">
    <%= @post_items.each do |post| %>
    <%= link_to image_tag(post.photo.url(:medium), style: 'height: 300px; width: 500px;'), modal_post_path(post), data: {:toggle => 'modal', :target => '#reusable_modal'}, lazy: true %>

   <div id="post-modal" class="modal fade"></div>

      <!-- Modal -->
      <div class="modal fade" id="reusable_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">

          </div>
        </div>
      </div>
<% end %>

<script type= "text/javascript">
  $(document).on('page:change', function () {
      $(document).on('click', '#reusable_modal [data-dismiss="modal"]',
          function (e) {
            $(e.target).removeData('bs.modal');
            $('#reusable_modal').find('.modal-content').empty();
          });
      $(document).on('click', '[data-target="#reusable_modal"]', function (e) {
        $("#reusable_modal").find(".modal-content").load($(this).attr("href"));
      });
    });
</script>
</div>

帖子/Modal.html.erb

<div class="modal-header">
  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
  <i><%= image_tag(@post.user.avatar_url(:thumb), class: 'round-image-50') %></i>
  <h4 class="modal-title" id="myModalLabel" style="margin-left: 60px; margin-top: -42px;"><%= post.user.username %></h4>
</div>
<div class="modal-body">
  <% if @post.photo.present? %>
  <%= image_tag(@post.photo.url(:large), style: 'max-width: 570px;') %>
  <% end %>
  <div class="modal_post_pos">
    <%= sanitize content_with_emoji(@post.body) %>
  </div>
</div>
<div class="modal-footer">
  <%= render partial: 'comments/template', locals: {commentable: @post, new_comment: @comment} %>
</div>

Users_Controller.rb

 def show
        if params[:id].to_s.match(/^[0..9]+$/) && !User.friendly.exists?(params[:id])
          render 'public/404.html', status: 404
        else
          @user = User.friendly.find(params[:id])
          @post_items = @user.posts.paginate(page: params[:page])
        end
  end

Posts_Controller.rb

def modal
    render layout: false
 end

 def show
    @post = Post.find(params[:id])
    @new_comment = Comment.build_from(@post, current_user.id, "")
    respond_to do |format|
      format.html
      format.js
      format.json {render json: @post }
    end
  end

Routes.rb

resources :posts, except: [:edit, :update] do
    member do
      get 'like', to: 'posts#like'
      get 'dislike', to: 'posts#unlike'
      get :modal
    end
  end

服务器日志

Started GET "/posts/13/modal" for 127.0.0.1 at 2016-04-11 11:41:00 -0400
  ActiveRecord::SchemaMigration Load (0.5ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by PostsController#modal as HTML
  Parameters: {"id"=>"13"}
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 5]]
  Rendered posts/modal.html.erb (47.5ms)
Completed 500 Internal Server Error in 240ms (ActiveRecord: 1.5ms)

NoMethodError - undefined method `user' for nil:NilClass:
  app/views/posts/modal.html.erb:5:in `_app_views_posts_modal_html_erb__227267806_63456696'

【问题讨论】:

  • 你的问题是什么??
  • 如何在引导模式中加载显示操作。当我点击 link_to show 按钮时,它说的是 nilclass。当我不使用模式时,我会自动转到 show.html.erb 页面。所以,这绝对是模态体本身内部的链接的问题。 不起作用。
  • 尝试将所有 show 代码添加到 modal-body div 本身..看看是否有效..不要将其分离到 partial
  • 这似乎行得通。可能是一种混乱的方法,但如果我需要进行更改,至少我知道代码的所有逻辑位于何处。谢谢。
  • 那确实是“不是 Rails”的方法,为了实现它,您可能必须将完整的 modal 块取出到 _post 部分..请尝试看看这种方法是否有效。

标签: javascript jquery ruby-on-rails twitter-bootstrap ruby-on-rails-4


【解决方案1】:

由于您没有在 _posts 部分上定义任何实例变量 @post 并且仍在尝试在 _posts 内调用它,因此会引发错误。

如果您想使用 Bootstrap Modal 而不需要额外的 js 脚本,解决此问题的方法是将 _post 部分代码带到 _posts 部分本身和 &lt;% end %&gt; 模态之后的循环。

<% @post_items.each do |post| %>

<%= link_to image_tag........................

<!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">Post Show</h4>
              </div>
              <div class="modal-body">
             # complete partial code goes here 
              </div>
            </div>
          </div>
        </div>
<% end %>

显然,上述方法对性能不利,因为它会在不需要它的情况下渲染所有内容。

更好的方法是使用AjaxjQuery(我的偏好)。监听此button 事件(onClick)并使用ajax get 方法动态加载模式。考虑考虑这种方法以获得更好的性能。


我所说的第二种解决方案在这里得到了很好的解释:https://stackoverflow.com/a/22144587/2545197

【讨论】:

  • 你能写出一个完整的解决方案吗?
  • 我到处找了一个明确的解决方案。我能找到的最多的是引导模式内部的表单。
  • @RailzWithLove2035 刚刚添加了一个解决方案链接,请看一下。这就是我说的那个。
【解决方案2】:

也许是这样的?

在你的 JS 中

var $modal = $('#ajax-modal');

$.fn.modalmanager.defaults.backdropLimit = 1;

$('.modal-link').on('click', function(){
  var modal_url = $(this).data("modal-url");

  if(modal_url != null){
    // create the backdrop and wait for next modal to be triggered
    $('body').modalmanager('loading');

    $modal.empty().load(modal_url, '', function(){
      $modal.modal();
      // Any callback functions such as let's say selectpicker
      // $('#ajax-modal .selectpicker').selectpicker('refresh');
    });
    return false;
  }
});

在ERB中

<%= link_to 'Show', post_path(@post), class: 'modal-link', data: { modal_url: post_path(@post) } %>

【讨论】:

  • 找不到 'modalmanager' - 你使用的是什么 JS 文件?我将更新这篇文章以包含我采用的新方法。
【解决方案3】:

我通过简单地渲染模式显示视图的文件而不是正常的显示操作来解决这个问题。

  def show
    @post = Post.find(params[:id])
    @new_comment = Comment.build_from(@post, current_user.id, "")
    respond_to do |format|
      format.html {render :file => "posts/modal", layout: false}
      format.js {render :file => "posts/modal", layout: false}
      format.json {render json: @post }
    end
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2016-07-24
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多