7

I'm having an issue using a custom helper method in my Rails (3.0) app to output the required html.

I have the following call in my partial view: _label.html.erb

<% display_resource "Diamond", @resource.diamond %>

And in the resource_helper.rb file:

module ResourceHelper
   def display_resource(display_name, value)
      "<tr><td>#{display_name} </td><td>#{value.to_s}%</td></tr>" if value > 0
   end
end

The intended output is:

<tr>
  <td>Diamond</td>
  <td>15%</td>
<tr>

*granted, without the formatting, and the 15 is arbitrary

If I use the <%= ... %> when performing the method call, it'll output the string correctly, but it won't be html (ie I'll see "<tr><td>Diamond </td><td>15%</td></tr>" as opposed to "Diamond 15%")

What am I doing incorrectly?

2
  • Main reason why it isn't printing is because you use <% %> instead of <%= %> Commented Sep 30, 2010 at 14:28
  • If I used <%=...%> it'd output the string, but it would be the actual string (as that's the default behavior of rails now - to prevent XSS and other type of security holes that could arise) Commented Sep 30, 2010 at 15:00

1 Answer 1

10

You need to mark the string returned as "raw" and then use <%= %>

module ResourceHelper
   def display_resource(display_name, value)
      raw("<tr><td>#{display_name} </td><td>#{value.to_s}%</td></tr>") if value > 0 # string wrapped in raw
   end
end
Sign up to request clarification or add additional context in comments.

4 Comments

I just migrated an app to Rails 3, and I'd like to ask: this is a new behavior in how Rails 3 treats HTML Safe strings, correct?
@Robbie - I believe so - thus why I had this issue (but didn't know how to rectify it. Thanks for the help Rob!
Yes, this is the new way rails renders text. By default, all text rendered between <%= .. %> is escaped and you need to use raw() if you have some html that needs to be displayed
Your smart and I appreciate your help.

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.