views:

149

answers:

3

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;
A: 

<%= h my_variable %> h() is a helper method that html escapes whatever is passed to it.

<b>Some Bolded Text</b> would show in the browser window.

&lt;b&gt;Some Bolded Text&lt;/b&gt; would show in the page HTML source.

<%= my_variable %> should simply produce the html output.

Some Bolded Text would show in the browser window.

<b>Some Bolded Text</b> would show int the page HTML source.

Nate
Thanks Nate, but that's not what I'm seeing.<%= my_variable %>outputs:<b>Some Bolded Text</b>I am using Rails 3.0 if that makes any difference.
deadkarma
This is a rails3 specific question. Rails3 is meant to eliminate any need for h() calls.
Scott S.
@Scott S. - The question didn't specify Rails 3 when I answered it - look at the edit history.
Nate
A: 

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) %>
solo
Thanks solo, but I'd like the HTML tags to be intact and rendered in the page
deadkarma
+3  A: 

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.

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