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 (<
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 < 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 %>
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.