Rails 请问 redcarpet 如何增加 anchor?

eva · 2013年11月15日 · 最后由 eva 回复于 2013年11月15日 · 3195 次阅读

我的代码如下:(环境 ruby 1.8.7 rails 2.3.14) application_helper.rb:

require 'redcarpet'
require 'pygments'
module ApplicationHelper
  class HTMLwithPygments < Redcarpet::Render::HTML
    def block_code(code, language)
      Pygments.highlight(code, :lexer => language)
    end
  end

  def markdown(text)
    renderer = HTMLwithPygments.new(:hard_wrap => true, :with_toc_data => true)
    options = {
      :autolink => true,
      :no_intra_emphasis => true,
      :fenced_code_blocks => true,
      :lax_html_blocks => true,
      :strikethrough => true,
      :superscript => true,
      :lax_spacing => true
    }
    Redcarpet::Markdown.new(renderer, options).render(text).html_safe
  end 
end

view:

<%= markdown(File.read(@filename)) %>

文件是本地的静态 md 文件:

- [Header Files](#header-files)
...
# Header Files
...

但是最终生成的 html 如下:

 <a href="#header-files">Header Files</a>
....
<h1 id="toc_1">Header Files</h1>

问题就出在超连接里是#header-files,而 h1 里是 toc_1 请问我的 md 文件里 header-files 后面应该写成 toc_1 才行么? 但这个文件是从 github 下 clone 下来的,我看 github 生成的是:

<h1>
<a class="anchor" href="#header-files" name="header-files">
<span class="octicon octicon-link"></span>
</a>
Header Files
</h1>

这个 github 特殊处理了么?还是有什么参数直接加一下就好?

看看这个链接:https://github.com/vmg/redcarpet/pull/186

应该是要设置 with_toc_data 这个参数。

@codeframe with_toc_data 我已经加过了 我也是搜索到了https://github.com/vmg/redcarpet/pull/186 这个连接,发现 3 天前状态又变成 open 了,不确定和我使用的版本是不是也有关系。不过按照https://gist.github.com/courtenay/5454972 这个的做法就可以搞定了,当然要跟 github 的效果一样还要处理一些大小写和特殊字符的转换。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号