How to Display Brackets Correctly in Code in User Comments?

231 views Asked by At

When a user posts a comment on my site, I run it through a sanitized markdown formatter on the backend and then display it on the site.

However, this causes the less-than and greater-than signs (< and >) to come out with their HTML codes (&lt; and &rt;) inside the user's code examples (which gets marked with <pre> and <code> tags). The brackets display correctly outside of code, but how do I fix it so they show up correctly inside code?

In short, I want what now shows up as:

 if(a &lt; b)

To show up as:

if(a < b)

This is my code in the helper for marking down the user's comment:

def comment_markdown(text)
  renderer = Redcarpet::Render::HTML.new()
  markdown = Redcarpet::Markdown.new(renderer)
  safe_text = sanitize text, tags: %w(b i code pre br p)
  markdown.render(safe_text).html_safe
end

It's called in the view:

 <%= comment_markdown comment.text %>
2

There are 2 answers

0
am-rails On

I think I'll just use Redcarpet's filter_html: true option to prevent any security issues from iframes and the like. Then I don't need to sanitize the text, so it doesn't escape text inside pre tags, and it displays normally. I just need to see how to configure it so users can't use distracting things like Headers.

2
Chowlett On

Rails already HTML-safe's text for display in views; so with your call to .html_safe in the comment_markdown method, it's getting escaped twice.

Simply remove your call to .html_safe:

def comment_markdown(text)
  renderer = Redcarpet::Render::HTML.new()
  markdown = Redcarpet::Markdown.new(renderer)
  safe_text = sanitize text, tags: %w(b i code pre br p)
  markdown.render(safe_text)
end