1

I'm using Redcarpet gem for markdown and i wanna to generate automatic anchors for h2 titles to allow linking to each section.

show.html.erb

<div class = "content"><%= markdown(@post.body) %></div>

application_helper.rb

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 = {
    :fenced_code_blocks => true,
    :no_intra_emphasis => true,
    :autolink => true,
    :strikethrough => true,
    :lax_html_blocks => true,
    :superscript => true,
  }
  Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end

I read about :with_toc_data => true but it doesn't works for me. I added it in options area.

Bryan Ash
  • 4,385
  • 3
  • 41
  • 57
user1625602
  • 63
  • 1
  • 6

1 Answers1

0

I do the same thing as you describe which basically is

Redcarpet::Markdown.new(
  Redcarpet::Render::HTML.new(with_toc_data: true), {}
).render(text)

My view contains the following code

- @article.description.scan(/(#+)(.*)/).each do |menu_item|
  = content_tag(:a, menu_item[1], :href => "##{menu_item[1].downcase.strip.gsub(" ","-")}")

Maybe this helps.

Christian
  • 4,902
  • 4
  • 24
  • 42