« Moth | Main | Pink Fungus »

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)

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)

Now my images display properly.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
All HTML will be escaped. Hyperlinks will be created for URLs automatically.