HTML-Pipeline 是一个轻量级框架,可用于将用户的内容转换为 HTML 格式。
HTML-Pipeline 提供了一些可链接的、基于 DOM 的 HTML 过滤器,且支持将过滤器组成管道。
用法
过滤器采用 HTML 字符串或 Nokogiri::HTML::DocumentFragment
,可以对内容进行操作,然后输出对应的结果。
如,将 Markdown 源代码转换为 Markdown HTML :
require 'html/pipeline' filter = HTML::Pipeline::MarkdownFilter.new("Hi **world**!") filter.call
过滤器可以组合成一个管道,每个过滤器将输出传递给下一个过滤器的输入。如果你想让内容通过 Markdown 过滤且语法突出显示,可以创建以下管道:
pipeline = HTML::Pipeline.new [ HTML::Pipeline::MarkdownFilter, HTML::Pipeline::SyntaxHighlightFilter ] result = pipeline.call <<-CODE This is *great*: some_code(:first) CODE result[:output].to_s
输出:
<p>This is <em>greatem>:p> <pre><code>some_code(:first) code>pre>
如果要为 HTML 格式的代码生成 CSS,请使用 Rouge CSS Theme #css
方法。rouge
是 SyntaxHighlightFilter
的依赖项。
有些过滤器接受可选的上下文 且/或 结果 哈希,用于在管道中的过滤器之间传递参数和元数据。例如,如果你不想使用 GitHub 格式的 Markdown,可以在上下文哈希中传递一个选项:
filter = HTML::Pipeline::MarkdownFilter.new("Hi **world**!", :gfm => false) filter.call
用例
为应用的不同部分定义不同的管道。
# The context hash is how you pass options between different filters. # See individual filter source for explanation of options. context = { :asset_root => "http://your-domain.com/where/your/images/live/icons", :base_url => "http://your-domain.com" } # Pipeline providing sanitization and image hijacking but no mention # related features. SimplePipeline = Pipeline.new [ SanitizationFilter, TableOfContentsFilter, # add 'name' anchors to all headers and generate toc list CamoFilter, ImageMaxWidthFilter, SyntaxHighlightFilter, EmojiFilter, AutolinkFilter ], context # Pipeline used for user provided content on the web MarkdownPipeline = Pipeline.new [ MarkdownFilter, SanitizationFilter, CamoFilter, ImageMaxWidthFilter, HttpsFilter, MentionFilter, EmojiFilter, SyntaxHighlightFilter ], context.merge(:gfm => true) # enable github formatted markdown # Define a pipeline based on another pipeline's filters NonGFMMarkdownPipeline = Pipeline.new(MarkdownPipeline.filters, context.merge(:gfm => false)) # Pipelines aren't limited to the web. You can use them for email # processing also. HtmlEmailPipeline = Pipeline.new [ PlainTextInputFilter, ImageMaxWidthFilter ], {} # Just emoji. EmojiPipeline = Pipeline.new [ PlainTextInputFilter, EmojiFilter ], context
评论