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:
<b>Some Bolded Text</b>
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:
<b>Some Bolded Text</b>
<%= 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.
<b>Some Bolded Text</b>
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.
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) %>
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.