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

前端 未结 2 398
慢半拍i
慢半拍i 2021-02-06 04:51

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

$(\"#flash_message\").html(\"<%= escape_javascript(content_tag(:p, flash[:note], :class =&         


        
2条回答
  •  旧时难觅i
    2021-02-06 05:35

    Yes, you may create an app/views/shared/_flash_messages.js.rjs partial, which you can then render from anywhere (e.g. 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 (e.g. layouts/application.erb), add e.g.:
        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 (e.g. controller/action.js.rjs), add e.g.:
        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] %>
    
    <%= h(flash[:error]) %>
    <% flash.discard(:error) %> <% elsif flash[:notice] %>
    <%= h(flash[:notice]) %>
    <% flash.discard(:notice) %> <% else %>

    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
    

提交回复
热议问题