I'm using redcarpet gem with Ruby on Rails 7 to render Markdown as HTML. The problem is that is not rendering correctly the code blocks, it is rendering as:
<code class="ruby">
def func
puts "Hello there"
end
</code>
The correct output should be the above code without the code tags, and if I try to render different language the output is the same with the code tags.
The HTML rendered is the next:
<pre>
<code data-highlighted="yes" class="hljs language-ruby">
"<code "
<span class="hljs-keyword">class</span>
"="
<span class="hljs-string">"ruby"</span>
"> "
<span class="hljs-keyword">def</span>
<span class="hljs-title function_">func</span>
" puts "
<span class="hljs-string">"Hello there"</span>
<span class="hljs-keyword">end</span>
" <"
<span class="hljs-regexp">/code></span>
</code>
</pre>
Here is my code:
The function that renders the Markdown
def markdown(text)
options = {
no_links: false,
hard_wrap: true,
link_attributes: { target: "_blank" }
}
extensions = {
hard_wrap: true,
autolink: true,
no_intra_emphasis: true,
tables: true,
fenced_code_blocks: true,
strikethrough: true,
lax_spacing: true,
space_after_headers: true,
quote: true,
footnotes: true,
highlight: true,
underline: true
}
renderer = Redcarpet::Render::HTML.new(options)
Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end
The code where I call the markdown function:
<p class="break-words line-clamp-3"><%= markdown(post.body) %></p>
post.body contains all the Markdown text, for this example the text that sent to the markdown mehtod is:
Output of post.body is
irb(main):005> Post.find(86).body
Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT $2 [["id", 86], ["LIMIT", 1]]
=> "```ruby\r\n\r\ndef func\r\n puts \"Hello there\"\r\nend\r\n\r\n```"
irb(main):006>
In the form to create a new post I have a text area and I'm allowing this field in the params method, I believe this is not the problem. Anyone who face to this problem already and can help me to solve this error please?
Right now you are rendering the Markdown to HTML and then passing all of that through highlight.js which results in your output.
Simplest solution and keep syntax highlighting is to override the way Red Carpet generates code blocks
For Example
And then just replace this
renderer = Redcarpet::Render::HTML.new(options)withrenderer = CustomRender.new(options).Example