How to Inhibit Escaping in Rails3 ActionView Custom Helpers
I had bits of code like this scattered throughout my Rails3 views:
<%= image_tag(thumbnail_image_path(@image.id)) %>
I wanted to enclose each image_tag call in a <div></div> pair to allow styling, so I wrote the following custom helper and placed it in app/helpers/application_helpers.rb:
def thumbnail_block(image_id) "<div>#{image_tag(thumbnail_image_path(image_id))}</div>" end
I then replaced the calls to image_tag in my views with calls to thumbnail_block:
<%= thumbnail_block(@image.id) %>
However, instead of displaying the images, this displayed the HTML code in the browser window. Rails3 was automatically escaping the string produced by the new custom helper.
A search on Google lead me to this answer by Mike Fisher at StackOverflow and this post by Yehuda Katz at Rails Dispatch. These gave me the solution: the custom helper needs to mark the string as html_safe before returning it:
def thumbnail_block(image_id) "<div>#{image_tag(thumbnail_image_path(image_id))}</div>".html_safe end
Now my images display properly.
Reader Comments