Tintin81
Tintin81

Reputation: 10215

How to return raw HTML from Rails content_tag helper function?

In my Rails 4 app I have this helper function:

def plan_interval
  content_tag(:span) do
    "per" +
    content_tag(:span) do
      links = []
      %w(week month year).each do |i|
        links << link_to(i, nil)
      end
      links.join().html_safe
    end
  end
end

Can somebody tell me how to return this in a raw fashion? Right now, I am getting the unescaped HTML which doesn't look very pretty.

Thanks for any help.

Upvotes: 1

Views: 2589

Answers (1)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

You are concatenating a safe string returned from the inner content_tag call to an unsafe string, "per". This results in an unsafe string which gets escaped. Make sure that all string operands are html_safe or that the resulting string is HTML safe.

def plan_interval
  content_tag(:span) do
    "per".html_safe +
    content_tag(:span) do
      links = []
      %w(week month year).each do |i|
        links << link_to(i, nil)
      end
      links.join().html_safe
    end
  end
end

Upvotes: 5

Related Questions