[英]DRY up js.erb files (include another js.erb file)
我的大多数js.erb文件底部都包含这样的内容:
$("#flash_message").html("<%= escape_javascript(content_tag(:p, flash[:note], :class => "note")) %>");
$("#flash_message").fadeOut(2000);
$("#loading").remove();
我想将这些行移动到一个单独的文件中,然后从我的每个js.erb文件中调用该文件。 有可能吗?
最好的祝福。 AsbørnMorell
是的,您可以创建一个app/views/shared/_flash_messages.js.rjs
partial,然后可以从任何地方(例如从其他rjs
partials)渲染。
我在这些应用程序中的方法如下:
对于可能有闪存的非AJAX响应:
layouts/application.erb
),添加例如: render :partial => 'shared/flash_messages.html.erb'
对于可能还需要显示flash消息的AJAX响应,我添加了以下rjs
代码:
rjs
响应中(例如controller/action.js.rjs
),添加例如: render :partial => 'shared/flash_messages.js.rjs'
如果两个部分执行渲染闪存所必需的操作,则根据需要调用flash.discard(:error)
或flash.discard(:notice)
。
示例app/views/shared/flash_messages.html.erb
文件:
<% if flash[:error] %>
<div id="flash_message" class="error"><%= h(flash[:error]) %></div>
<% flash.discard(:error) %>
<% elsif flash[:notice] %>
<div id="flash_message" class="notice"><%= h(flash[:notice]) %></div>
<% flash.discard(:notice) %>
<% else %>
<div id="flash_message" style="display: none;" />
<% end %>
示例app/views/shared/flash_messages.html.rjs
文件:
if !flash[:error].blank?
page['flash_message'].
replace_html(flash[:error]).
removeClassName('notice').
addClassName('error').
show()
else
page['flash_message'].
replace_html(flash[:notice]).
removeClassName('error').
addClassName('notice').
show()
end
也许是<%= render :partial => 'common' %>
?
http://api.rubyonrails.org/classes/ActionController/Base.html#M000633
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.