【发布时间】:2019-03-20 13:27:12
【问题描述】:
问题
我正在使用 gem "render_async" 来异步渲染内容。
当我访问像localhost:3000/people 这样的页面时,内容按预期异步呈现。
但是,如果内容位于通过 ajax 加载的部分内部,则内容不会异步呈现。我不明白为什么它不起作用,我不知道如何解决它。
如果 render_async 在通过 ajax 加载的部分内部,我该如何使用它?
gem 渲染异步:https://github.com/renderedtext/render_async
什么有效
当我调用像 localhost:3000/people 这样的索引页面时,render_async 会按预期工作。
这是有效的代码:
人/index.html.erb
<h1>People</h1>
...
<div class="people">
<%= render partial: "people/show", collection: people, as: :person %>
</div>
在 people-div 中,正在加载部分 _show.html.erb。
人/_show.html.erb
<h1>Person</h1>
...
<%= render_async render_shared_path(parent_type: "Person", parent_id: person.id), 'data-turbolinks-track': 'reload', error_message: '<p>Sorry, users loading went wrong :(</p>' do %>
Shared lädt!
<% end %>
此代码按预期工作。 render_async 加载一个名为 _children.html.erb 的部分。当用户访问 people/index.html.erb 时,所有 _children-partials 都被异步加载。
什么不起作用
在 people/index.html 上,当用户按下按钮时,people-div 正在通过 ajax 重新加载。以下是人员 div 的重新加载方式:
var people_div = ".people";
$( people_div ).fadeOut( "fast", function() {
content = $("<%= escape_javascript( render 'people/people', people: @people ) %>")
$(people_div).replaceWith(function(){
return $(content).hide().fadeIn("fast");
});
});
正在重新加载的代码与 people/index.js 中的代码相同。只有参数改变。
重新加载 people-div 后,不会异步呈现任何内容。 _children-partials 未加载。rails 控制台或 Web 控制台中没有消息。
唯一可见的是占位符:“Shared lädt!”。
可能是什么问题?
代码
_show.html.erb
<%= render_async render_shared_path(parent_type: "Person", parent_id: person.id), 'data-turbolinks-track': 'reload', error_message: '<p>Sorry, users loading went wrong :(</p>' do %>
Shared lädt!
<% end %>
routes.rb
#render
get '/render_shared', to: 'render#render_shared', as: 'render_shared'
render_controller.rb
def render_shared
parent_type = params[:parent_type]
parent_id = params[:parent_id]
@parent = parent_type.singularize.classify.constantize.find(parent_id)
render partial: "shared/children"
end
_children.html.erb
<% parent = parent || @parent %>
<div class="shared-<%=parent.class.name.downcase%>-<%=parent.id%>">
<p>
<a class="btn btn-link btn-sm" data-toggle="collapse" href=".address-<%= parent.id %>-<%= parent.class.to_s.downcase %>" role="button" aria-expanded="false" aria-controls="collapseExample">
<%= fa_icon "address-card" %> Adresse anzeigen
</a>
</p>
<div class="collapse mb-2 address-<%= parent.id %>-<%= parent.class.to_s.downcase %>" >
<%= render "addresses/show", address: parent.address %>
</div>
</div>
application.html.erb
<head>
<title>MyApp</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= content_for :render_async %>
</head>
【问题讨论】:
-
请在您写问题时...提出更好的问题描述。工作的事情与正在发生的事情相比是什么?另外,添加一个 jquery 标记或基于它进行一些搜索……这可能是重复的,但太忙了,无法过滤它们。
标签: ruby-on-rails ruby-on-rails-5 render