Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
Albzi Avatar asked Jul 19 '13 13:07

Albzi


People also ask

How do I use flash in Ruby on Rails?

In order to implement flash in your own apps, there's a specific set of steps that must be taken. You first call and set flash in your action controller. You must tell flash precisely what you want it to persist forward. Redirect your action controller to the full-page reload of your choice.

What is flash in Ruby on Rails?

A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions. Example messages: “Password changed correctly” (confirmation) “User not found” (error)


2 Answers

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.

like image 62
Bachan Smruty Avatar answered Oct 19 '22 02:10

Bachan Smruty


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>
like image 3
Krishna Rani Sahoo Avatar answered Oct 19 '22 03:10

Krishna Rani Sahoo