0

In a Rails app I have helper methods that render html snippets, e.g. Twitter bootstrap fonts

def edit_icon
  content_tag(:i, "", :class=>'icon-edit')
end

I want to display this in a link anchor with additional text appended. e.g.

<%= link_to "#{edit_icon} Edit this Record", edit_record_path(@record) %>

This is currently rendering the content_tag as a string, not as HTML. How do I render it as HTML?

I experimented with <%= link_to "#{raw edit_icon} and <%= link_to "#{edit_icon.html_safe}, but these don't seem to be what I need in this case.

Thanks for any ideas.

1 Answer 1

5

The issue is Rails string interpolation transforms the HTML output of content_tag into a "safe" format. The fixes you tried both operate before string interpolation is applied, which won't work

Fixing the problem requires just a small change: move the method call outside of the string.

Do this:
    <%= link_to edit_icon + "Edit this Record", edit_record_path(@record) %>
Instead of:
     <%= link_to "#{edit_icon} Edit this Record", edit_record_path(@record) %>
Sign up to request clarification or add additional context in comments.

2 Comments

perfect! Can you suggest any good sources of information that explain this? Or, in other words, where should I have been looking to figure this out myself? Thanks once again!
Here's a pretty good explanation yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0 I think I learned this from reading The Rails 3 Way, by Obie Fernandez, about a year ago.

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.