deadkarma
deadkarma

Reputation: 3144

How does one NOT html_encode a variable in rails?

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;

Upvotes: 5

Views: 1370

Answers (2)

scottd
scottd

Reputation: 7474

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.

Upvotes: 8

kwarrick
kwarrick

Reputation: 6240

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) %>

Upvotes: 0

Related Questions