繁体   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