簡體   English   中英

Redcarpet / Bluecloth不允許標題?

[英]Redcarpet/Bluecloth not allowing headers?

有沒有辦法使用Redcarpet或Bluecloth,這樣當它插入降價時它不會產生任何標題?

例如:

#header 1

收益率:

標題1

標題1(首選)

和:

##header 2

收益率:

標題2

標題2(首選)

好吧,你可以在Markdown中轉義字符:

# header 1
\# header 1

## header 2
\## header 2

...給:

標題1

#header 1

標題2

##標題2

如果您不想這樣做,或者您正在解析其他人的Markdown並且沒有選擇,我建議您預先處理收到的Markdown以執行上述操作:

def pound_filter text
  text.gsub /^#/, '\#'
end

使用Redcarpet,您可以驗證它是否有效:

text = <<-END
  # Hello
  ## World
END

Markdown.new(text.to_html)
# =>  <h1>Hello</h1>
#
#     <h2>World</h2>

Markdown.new(pound_filter text).to_html
# =>  <p># Hello
#     ## World</p>

當然,因為HTML中的換行符實際上不會這樣呈現 - 它將顯示為一行:

# 你好,世界”

......你可能想要增加:

def pound_filter text
  text.gsub( /((\A^)|([^\A]^))#/ ) {|match| "\n" == match[0] ? "\n\n\\#" : '\#' }
end

pound_filter text
# =>  \# Hello
#
#     \## World

Markdown.new(pound_filter text).to_html
# =>  <p>\# Hello</p>
#
#     <p>\## World</p>

這最后會顯示為:

# 你好

##世界

不幸的是,你最終會進入這樣一個奇怪的領域,其中標題在引號內:

> ## Heading

......但我把它作為練習留給讀者。

在這里看到類似的解決方案:

class RenderWithoutWrap < Redcarpet::Render::HTML
  def postprocess(full_document)
    Regexp.new(/\A<p>(.*)<\/p>\Z/m).match(full_document)[1] rescue full_document
  end
end

它會刪除所有<p></p>標記。 我就這樣使用它並且它起作用了。 我將該類放在名為/config/initializers/render_without_wrap.rb的新文件中。 你可以為所有<h1> - <h6>標簽做類似的事情

class RenderWithoutHeaders < Redcarpet::Render::HTML
  def postprocess(full_document)
    Regexp.new(/\A<h1>(.*)<\/h1>\Z/m).match(full_document)[1] rescue full_document
    Regexp.new(/\A<h2>(.*)<\/h2>\Z/m).match(full_document)[1] rescue full_document
    Regexp.new(/\A<h3>(.*)<\/h3>\Z/m).match(full_document)[1] rescue full_document
    ...(you get the idea)
  end
end

然后你可以像這樣使用它

def custom_markdown_parse(text)
  markdown = Redcarpet::Markdown.new(RenderWithoutHeaders.new(
    filter_html: true,
    hard_wrap: true,
    other_options: its_your_call
  ))
  markdown.render(text).html_safe
end

我沒有測試過,但這是一個想法。

1.您應該能夠使用反斜杠轉義降價源文本:

\# not a header

你也可以修補它:

module RedCloth::Formatters::HTML

  [:h1, :h2, :h3, :h4, :h5, :h6].each do |m|
    define_method(m) do |opts|
      "#{opts[:text]}\n"
    end
  end

end

鑒於對Markdown預解析很困難,並且Markdown允許插入HTML,那么如何從生成的HTML中刪除標題元素呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM