Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I textile and sanitize html?

Now i ran into some stupid situation. I want the users to be able to use textile, but they shouldn't mess around with my valid HTML around their entry. So I have to escape the HTML somehow.

  • html_escape(textilize("</body>Foo")) would break textile while

  • textilize(html_escape("</body>Foo")) would work, but breaks various Textile features like links (written like "Linkname":http://www.wheretogo.com/), since the quotes would be transformed into &quot; and thus not detected by textile anymore.

  • sanitize doesn't do a better job.

Any suggestions on that one? I would prefer not to use Tidy for this problem. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For those who run into the same problem: If you are using the RedCloth gem you can just define your own method (in one of your helpers).

def safe_textilize( s )
  if s && s.respond_to?(:to_s)
    doc = RedCloth.new( s.to_s )
    doc.filter_html = true
    doc.to_html
  end
end

Excerpt from the Documentation:

Accessors for setting security restrictions.

This is a nice thing if you‘re using RedCloth for formatting in public places (e.g. Wikis) where you don‘t want users to abuse HTML for bad things.

If filter_html is set, HTML which wasn‘t created by the Textile processor will be escaped. Alternatively, if sanitize_html is set, HTML can pass through the Textile processor but unauthorized tags and attributes will be removed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...