Rails 7中Redcarpet渲染Markdown代码块异常求助
Redcarpet + Rails 7 代码块渲染嵌套标签问题
使用Redcarpet gem搭配Rails 7渲染Markdown为HTML时,代码块出现异常嵌套<code>标签的问题:渲染后的<pre><code>内部会额外生成<code class="ruby">标签,导致语法高亮渲染混乱,正确输出应仅保留外层<pre><code>结构,并正确传递代码语言标识。
错误渲染输出
简化版错误结果
<pre class="lang-html prettyprint-override"><code><code class="ruby"> def func puts "Hello there" end </code> </code></pre>
实际生成的完整HTML
<pre class="lang-html prettyprint-override"><code><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> </code></pre>
相关代码
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
视图调用代码
<p class="break-words line-clamp-3"><%= markdown(post.body) %></p>
存储的Markdown内容(来自IRB)
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```"
补充说明
表单使用文本域输入Markdown内容,已在控制器params中允许该字段,排除输入存储环节问题,求解决代码块嵌套<code>标签的异常。
内容的提问来源于stack exchange,提问作者MauricioNC
相关产品推荐
相关产品推荐

