[英]Rails 3 - notice and error flash cannot be rendered in a partial
I was trying to clean up application.html.erb
, by moving parts of the layout into partials. 我试图通过将部分布局移动到部分来清理
application.html.erb
。 I had the following code for handling flash errors/notifications: 我有以下代码来处理闪存错误/通知:
<div id="flash">
<% if flash[:notice] %>
<h3 class="info_box"><%= flash[:notice] %></h3>
<% end %>
<% if flash[:error] %>
<h3 class="error_box"><%= flash[:error] %></h3>
<% end %>
</div>
This code worked fine in application.html.erb
, until I moved it into a file called " _flash.html.erb
" and replaced it with the following: 这段代码在
application.html.erb
工作得很好,直到我把它移到一个名为“ _flash.html.erb
”的文件中并用以下内容替换它:
<%= render 'layouts/flash' %>
In the partial the flash hash was not a recognized object and causes a "You have a nil object when you didn't expect it!" 在部分中,闪存哈希不是一个可识别的对象,并导致“当你没想到它时,你有一个零对象!” error.
错误。
I've move the code back to application.html.erb and all is good. 我已将代码移回application.html.erb,一切都很好。 But I couldn't find an answer for accessing the flash hash within a partial.
但我无法找到部分访问闪存哈希的答案。 Looking at the Rails Guide for "Rendering and Layouts" I can see that there are various ways for
render()
to pass variables into the partial, but I was unsuccessful in figuring it out. 看看Rails指南中的“渲染和布局”我可以看到
render()
有多种方法将变量传递给partial,但是我没有成功地搞清楚它。 Any ideas? 有任何想法吗?
Goliatone's solution seemed to work, but in the end it didn't. Goliatone的解决方案似乎有效,但最终却没有。 I found out that the reason this was not working for me was that I had named my partial
_flash
. 我发现这不适合我的原因是我已经命名了我的部分
_flash
。 Apparently Rails creates a local variable for the partial using the partial's name (without the "_"
character.) So I had a variable clash. 显然Rails使用部分名称为部分创建一个局部变量(没有
"_"
字符。)所以我有一个变量冲突。 As soon as I change the name of the partial to something other than _flash
everything worked perfectly. 只要我将部分名称更改为
_flash
其他_flash
一切都会完美运行。 I found the answer here: Rails flash[:notice] always nil 我在这里找到了答案: Rails flash [:notice]总是零
You can place the conditional check for flash in the layout, and if it exists then render the partial: 您可以在布局中对flash进行条件检查,如果它存在,则渲染部分:
<%= render 'layouts/flash' unless flash.nil?%>
Then, if it exists it will get rendered as expected. 然后,如果它存在,它将按预期呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.