Albzi
Albzi

Reputation: 15609

Adding HTML to ruby on rails flash message

I have a flash[:success] message which goes like this:

flash[:success] = "This text is now bold.". However, when I go to make the text bold, it just wraps HTML characters around the message, rather than actually turning bold.

<b>This text is now bold</b>

How can I go about including HTML into flash messages?

Upvotes: 16

Views: 14940

Answers (3)

Bachan Smruty
Bachan Smruty

Reputation: 5734

Use <%= flash[:success].html_safe %> in your view.

Whenever your flash[:success] is blank, it will show error due to html_safe. So it is better to use a condition.

So try with the following to prevent that error:

<%= flash[:success].html_safe unless flash[:success].blank? %>

You could also use .try to prevent that error:

<%= flash[:success].try(:html_safe) %>

And if you know there is content for sure, you can also try:

<%= raw flash[:success] %>

ERB-specific HTML display

On top of that, since you are using ERB, you can use h() method for HTML-escaped strings:

<%= h flash[:success] %>

Check out this tutorial on ERB for other options such as for displaying JSON or URL-encoded strings.

Upvotes: 23

Kyle Truscott
Kyle Truscott

Reputation: 1577

You can add arbitrary HTML to your flash message, but you'll need to user html_safe to render it unescaped.

flash[:error] = "<em>Crap!</em> We lost everything."

In the view:

<%= flash[:error].html_safe %>

Upvotes: 2

Krishna Rani Sahoo
Krishna Rani Sahoo

Reputation: 1539

save message as

flash[:success] = "<b>This text is now bold.</b>"

put in the html file as

<div class="notice">
<%=h flash[:notice]%>
</div>

Upvotes: 3

Related Questions