如何将 html 渲染到 Rails flash 消息/通知中?
我的 UsersController
有这个 destroy
操作:
def destroy
User.find(params[:id]).destroy
flash[:success] = "<i class=\"fa fa-check\"></i> Utilisateur supprimé.".html_safe
redirect_to users_url
end
当我调用此 destroy
操作时,flash 成功消息打印 html 标记而不是呈现它。
我试过 this回答,但我不知道如何使用它,因为我在 Controller 中而不是在 View 中,所以我没有使用 <%= %> 来嵌入代码。
最佳答案
如果有人遇到同样的问题,这里有一个对我有用的答案:
1st:正如 Justin Licata 所说,.html_safe
方法必须应用于 flash 的消息。
2nd :如果你想在你的消息中使用图标(在我的例子中是很棒的字体),将它放入你的消息字符串中是行不通的,你必须将它放入你的 中。 html
文件打印您的 flash 消息。 (灵感来自 this )
这是我在布局 application.html.erb
中渲染 flash 消息的代码:
<% flash.each do |message_type, message| %>
<div class="row" id="msgContainer">
<div class="callout callout-<%= message_type %>" id="flash_message">
<% if flash[:notice] %>
<i class="fa fa-info"></i>
<% end %>
<% if flash[:danger] %>
<i class="fa fa-exclamation-triangle"></i>
<% end %>
<% if flash[:success] %>
<i class="fa fa-check"></i>
<% end %>
<%= message.html_safe %>
</div>
</div>
<% end %>
这对我有用,希望能有所帮助。
关于html - 将 HTML 渲染到 Rails flash 消息中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535407/