Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML into Rails flash message

How to render html into Rails flash message/notice ?

I have this destroy action from my UsersController :

def destroy
  User.find(params[:id]).destroy
  flash[:success] = "<i class=\"fa fa-check\"></i> Utilisateur supprimé.".html_safe
  redirect_to users_url
end

When I call this destroy action, the flash success message print the html tag instead of render it.

I have try with this answer but I don't how to use it since I am in the controller and not in the view so I am not using <%= %> to embed the code.

like image 335
Arnaud Avatar asked Jul 11 '26 16:07

Arnaud


1 Answers

If someone encounter the same problem, here is an answer working for me :

1st : the .html_safe method has to be applied to the message of the flash as Justin Licata said.

2nd : if you want to use icons (Font awesome in my case) into your message, putting it into your message string will not work, you have to put it into your .html file which print your flash message. (Inspired from this)

Here is my rendering flash message code, into my layout application.html.erb :

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

This work for me, hope this can help.

like image 100
Arnaud Avatar answered Jul 14 '26 08:07

Arnaud