繁体   English   中英

干掉js.erb文件(包括另一个js.erb文件)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM