简体   繁体   中英

DRY up js.erb files (include another js.erb file)

Most of my js.erb files contains something like this at the bottom:

$("#flash_message").html("<%= escape_javascript(content_tag(:p, flash[:note], :class => "note")) %>");
$("#flash_message").fadeOut(2000);
$("#loading").remove();

I would like to move these lines into a seperate file and then call that file from each of my js.erb files. Is something like that possible?

Best regards. Asbørn Morell

Yes, you may create an app/views/shared/_flash_messages.js.rjs partial, which you can then render from anywhere (eg from other rjs partials.)

My approach in these kinds of applications has been as follows:

  • for non-AJAX responses that may have a flash:

    • in the layout (eg layouts/application.erb ), add eg:
      render :partial => 'shared/flash_messages.html.erb'
  • for AJAX responses that may also need to display a flash message, I added the following rjs code:

    • in each rjs response (eg controller/action.js.rjs ), add eg:
      render :partial => 'shared/flash_messages.js.rjs'

Where the two partials do the necessary to render the flash, then call flash.discard(:error) or flash.discard(:notice) as appropriate.

Sample app/views/shared/flash_messages.html.erb file:

<% 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 %>

Sample app/views/shared/flash_messages.html.rjs file:

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' %> , perhaps?

http://api.rubyonrails.org/classes/ActionController/Base.html#M000633

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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