0

I have input that may either be a string or be a string of html. I have figured out how to recognize whether or not the string is html, but I don't know how to have the browser interpret the string as html instead.

For example, instead of having <a href='www.google.com'> Click here!! </a> on the page, I would instead like to have the actual link render like: Click Here

View code where I am trying to do this:

<div class="description">    
  <%= p.description %>
<div>
2
  • could you paste your view code? Commented Jun 8, 2011 at 5:18
  • Sure, I added the line where I am trying to do this. Commented Jun 8, 2011 at 5:19

2 Answers 2

4

You need to mark the string as 'html safe' in one of two ways:

<%= raw @string %>

... or by explicitly marking the string as html_safe:

<%= @string.html_safe %>

However: Please bear in mind that if this input comes from untrusted users (i.e. anyone other than you!), then this could be a risky strategy, as it will allow cross site scripting attacks. Make sure you read the rails security guide for more information on this risk and how to effectively mitigate it.

Sign up to request clarification or add additional context in comments.

1 Comment

very hard to choose between these two answers. both very informative and helpful. going with this one because of the security tips. I hadn't thought of that. Then again, I don't think of security as much as I should
2

Sounds like you need to use the raw helper, if your code looks like this:

@your_bit_of_html = '<a href="www.google.com"> Click here!! </a>'

Then your view ERB should look like this:

<%= raw @your_bit_of_html %>

And, now that you've included a sample of your ERB:

<div class="description">    
  <%= raw p.description %>
<div>

Using raw assumes that you have properly encoded and cleansed any HTML that you're going to output so you'll need to exercise due caution.

2 Comments

The link to rubyonrails.org is not valid anymore.
@TrueSoft: Thanks, I updated it to match the current location of the raw helper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.