我知道我可以使用 ruby 中的 Kramdown 解析和呈现 HTML 文档,使用类似的东西
require 'kramdown'
s = 'This is a _document_'
Kramdown::Document.new(s).to_html
# '<p>This is a <i>document</i></p>'
在这种情况下,字符串 s
可能包含 Markdown 语法的完整文档。
然而,我想做的是解析 s
假设它只包含 span-level markdown 语法,并获取呈现的 html。特别是不应该有 <p>
, <blockquote>
,或者,例如 <table>
在呈现的 html 中。
s = 'This is **only** a span-level string'
# .. ??? ...
# 'This is <b>only</b> a span-level string'
我该怎么做?
最佳答案
我会使用 sanitize
gem 对输出进行后处理。
require 'sanitize'
html = Kramdown::Document.new(s).to_html
output = Sanitize.fragment(html, elements:['b','i','em'])
元素是允许标签的白名单,随便添加你想要的标签。该 gem 有一组预定义的白名单,但没有一个与您正在寻找的完全匹配。 (顺便说一句,如果您想要一个跨度中允许的所有 HTML5 元素的列表,请参阅 WHATWG's list of "phrasing content")。
我知道这没有标记 rails , 但为了使用 Rails 的读者的利益:使用内置的 sanitize helper .
关于ruby - 使用 Kramdown 渲染 span-level 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140588/