5

With Rails, If I have a variable with HTML content, how do I output it, unencoded in my view file?

This code, for example:

<% my_variable = "<b>Some Bolded Text</b>" %>
<%= my_variable %>

Outputs:

&lt;b&gt;Some Bolded Text&lt;/b&gt;

2 Answers 2

8

Are you using Rails 3 Beta? Rails 2 by default does not HTML escape your output, you usually have to use the h helper, see Nate's post. If you are using Rails 3 you need to either use the raw helper or set your string as html safe. Examples

<% my_variable = "<b>Some Bolded Text</b>" %>
<%= raw my_variable %>

Or

<% my_variable = "<b>Some Bolded Text</b>".html_safe %>
<%= my_variable %>   

Check your Rails version and get back to us.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Scott! That was it! I am using the Rails 3 Beta
0

ActionView::Helpers::TextHelper provides a method strip_tags, which instead of just escaping the tags, removes them completely.

source [reference]:

 def strip_tags(html)     
    return html if html.blank?
    if html.index("<")
      text = ""
      tokenizer = HTML::Tokenizer.new(html)
      while token = tokenizer.next
        node = HTML::Node.parse(nil, 0, 0, token, false)
        # result is only the content of any Text nodes
        text << node.to_s if node.class == HTML::Text  
      end
      # strip any comments, and if they have a newline at the end (ie. line with
      # only a comment) strip that too
      text.gsub(/<!--(.*?)-->[\n]?/m, "") 
    else
      html # already plain text
    end 
  end

<%= strip_tags(my_variable) %>

1 Comment

Thanks solo, but I'd like the HTML tags to be intact and rendered in the page

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.