Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML and Ruby on Rails - Display <br/> tags as line breaks, but other tags as strings

I'm working on my first Rails website, but I have a little problem: I want to display the <br/> tags as line breaks, but I also want to display the other tags as strings.

For example, the user input is:

<a href='#2'>Go to #2</a><br/><a href='#3'>Go to #3</a>

I want to display:

<a href='#2'>Go to #2</a>
<a href='#3'>Go to #3</a>

I know that I can display the <br/> tags as line breaks like this:

<%= simple_format @user_input %>

But the problem is that this command display:

Go to #2
Go to #3

And not:

<a href='#2'>Go to #2</a>
<a href='#3'>Go to #3</a>

Thank you in advance!

like image 299
ElonTheFreemason Avatar asked Nov 27 '25 03:11

ElonTheFreemason


1 Answers

Use the Rails sanitize helper method and whitelist the tags you want to allow and leave those out that you don't. All those left out would be stripped and shown as text. So in your case it would be something like

<%= sanitize @user_input, tags: %w(br) %>

For the sanitize method api info see http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize.

like image 107
Steve Carey Avatar answered Nov 28 '25 15:11

Steve Carey