Rails escaping HTML content by default?

5 views
Skip to first unread message

אריה גלזר

unread,
Feb 23, 2011, 3:43:48 AM2/23/11
to isra...@googlegroups.com
Hey
I have a Post class, that has a body field that contains some normal html text. When I print it in my template, it automatically escapes the html entities.
basically, when running these lines:

<% puts(post.body)%>
<%=post.body%>

the first line logs: <p>aaaa</p>
and the output is:  &lt p &gt aaaa &lt/p &gt

(not using ; so mail won't print entities).

Any idea where I need to look for fixing this issue?
--
Arieh Glazer
אריה גלזר
052-5348-561
http://www.arieh.co.il
http://www.link-wd.co.il

Reuven M. Lerner

unread,
Feb 23, 2011, 3:50:39 AM2/23/11
to isra...@googlegroups.com, אריה גלזר

Hi, Arieh.  You wrote:


I have a Post class, that has a body field that contains some normal html text. When I print it in my template, it automatically escapes the html entities.
basically, when running these lines:

<% puts(post.body)%>
<%=post.body%>

the first line logs: <p>aaaa</p>
and the output is:  &lt p &gt aaaa &lt/p &gt

(not using ; so mail won't print entities).

Any idea where I need to look for fixing this issue?
This is a feature, not a bug. :-)  As of Rails 2.3.10 (or thereabouts), as well as Rails 3, HTML is escaped by default, to avoid XSS attacks.

If you want the original (unescaped) text, you can use the "raw" function, as in:

<%= raw(post.body) %>

But of course, if post.body contains HTML, and especially <script> tags, you are inviting trouble.  Make sure to clean/sanitize the HTML before you display it, preferably by keeping a known set of tags (i.e., removing all but a known, safe subset), rather than removing a set of dangerous ones.

Reuven

-- 
Reuven M. Lerner -- Web development, consulting, and training
Mobile: +972-54-496-8405 * US phone: 847-230-9795
Skype/AIM: reuvenlerner

shmichael

unread,
Feb 23, 2011, 1:31:30 PM2/23/11
to isra...@googlegroups.com, אריה גלזר
And of course for HAML you just use != instead of = .
One more nail in ERB's coffin...

Akiva Levy

unread,
Mar 8, 2011, 5:03:06 PM3/8/11
to Israel.rb - the Israel Ruby & Israel Rails Developers group
Additionally, you can output it with html_safe, ie: <%=
post.body.html_safe %>
Reply all
Reply to author
Forward
0 new messages