You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>&lt;code class=&quot;ruby&quot;&gt;
  def func
    puts &quot;Hello there&quot;
  end
&lt;/code&gt;
</code></pre>

实际生成的完整HTML

<pre class="lang-html prettyprint-override"><code>&lt;pre&gt;
  &lt;code data-highlighted=&quot;yes&quot; class=&quot;hljs language-ruby&quot;&gt;
    &quot;&lt;code &quot;
    &lt;span class=&quot;hljs-keyword&quot;&gt;class&lt;/span&gt;
    &quot;=&quot;
    &lt;span class=&quot;hljs-string&quot;&gt;&quot;ruby&quot;&lt;/span&gt;
    &quot;&gt; &quot;
    &lt;span class=&quot;hljs-keyword&quot;&gt;def&lt;/span&gt;
    &lt;span class=&quot;hljs-title function_&quot;&gt;func&lt;/span&gt;
    &quot; puts &quot;
    &lt;span class=&quot;hljs-string&quot;&gt;&quot;Hello there&quot;&lt;/span&gt;
    &lt;span class=&quot;hljs-keyword&quot;&gt;end&lt;/span&gt;
    &quot; &lt;&quot;
    &lt;span class=&quot;hljs-regexp&quot;&gt;/code&gt;&lt;/span&gt;
  &lt;/code&gt;
&lt;/pre&gt;
</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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 21:57:31