[英]DRY up js.erb files (include another js.erb file)
Most of my js.erb files contains something like this at the bottom: 我的大多数js.erb文件底部都包含这样的内容:
$("#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. 我想将这些行移动到一个单独的文件中,然后从我的每个js.erb文件中调用该文件。 Is something like that possible?
有可能吗?
Best regards. 最好的祝福。 Asbørn Morell
AsbørnMorell
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.) 是的,您可以创建一个
app/views/shared/_flash_messages.js.rjs
partial,然后可以从任何地方(例如从其他rjs
partials)渲染。
My approach in these kinds of applications has been as follows: 我在这些应用程序中的方法如下:
for non-AJAX responses that may have a flash: 对于可能有闪存的非AJAX响应:
layouts/application.erb
), add eg: layouts/application.erb
),添加例如: 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: 对于可能还需要显示flash消息的AJAX响应,我添加了以下
rjs
代码:
rjs
response (eg controller/action.js.rjs
), add eg: rjs
响应中(例如controller/action.js.rjs
),添加例如: 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. 如果两个部分执行渲染闪存所必需的操作,则根据需要调用
flash.discard(:error)
或flash.discard(:notice)
。
Sample app/views/shared/flash_messages.html.erb
file: 示例
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 %>
Sample app/views/shared/flash_messages.html.rjs
file: 示例
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' %>
, perhaps? 也许是
<%= render :partial => 'common' %>
?
http://api.rubyonrails.org/classes/ActionController/Base.html#M000633 http://api.rubyonrails.org/classes/ActionController/Base.html#M000633
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.