add support to keep img tags when converting to html

This commit is contained in:
Régis Hanol 2017-04-28 22:14:46 +02:00
parent 51ee49aad2
commit aba76bace6
3 changed files with 16 additions and 5 deletions

View File

@ -194,7 +194,7 @@ module Email
end end
markdown, elided_markdown = if html.present? markdown, elided_markdown = if html.present?
markdown = HtmlToMarkdown.new(html).to_markdown markdown = HtmlToMarkdown.new(html, keep_img_tags: true).to_markdown
markdown = trim_discourse_markers(markdown) markdown = trim_discourse_markers(markdown)
EmailReplyTrimmer.trim(markdown, true) EmailReplyTrimmer.trim(markdown, true)
end end

View File

@ -6,7 +6,8 @@ class HtmlToMarkdown
def initialize(name, head="", body="", opened=false, markdown=""); super; end def initialize(name, head="", body="", opened=false, markdown=""); super; end
end end
def initialize(html) def initialize(html, opts={})
@opts = opts || {}
@doc = Nokogiri::HTML(html) @doc = Nokogiri::HTML(html)
remove_whitespaces! remove_whitespaces!
end end
@ -133,9 +134,13 @@ class HtmlToMarkdown
end end
def visit_img(node) def visit_img(node)
if @opts[:keep_img_tags]
@stack[-1].markdown << node.to_html
else
title = node["alt"].presence || node["title"].presence title = node["alt"].presence || node["title"].presence
@stack[-1].markdown << "![#{title}](#{node["src"]})" @stack[-1].markdown << "![#{title}](#{node["src"]})"
end end
end
def visit_a(node) def visit_a(node)
@stack[-1].markdown << "[" @stack[-1].markdown << "["

View File

@ -31,8 +31,14 @@ describe HtmlToMarkdown do
expect(html_to_markdown(%Q{<a href="https://www.discourse.org">Discourse</a>})).to eq("[Discourse](https://www.discourse.org)") expect(html_to_markdown(%Q{<a href="https://www.discourse.org">Discourse</a>})).to eq("[Discourse](https://www.discourse.org)")
end end
HTML_WITH_IMG ||= %Q{<img src="https://www.discourse.org/logo.svg" alt="Discourse Logo">}
it "converts <img>" do it "converts <img>" do
expect(html_to_markdown(%Q{<img src="https://www.discourse.org/logo.svg" alt="Discourse Logo">})).to eq("![Discourse Logo](https://www.discourse.org/logo.svg)") expect(html_to_markdown(HTML_WITH_IMG)).to eq("![Discourse Logo](https://www.discourse.org/logo.svg)")
end
it "keeps <img> with 'keep_img_tags'" do
expect(HtmlToMarkdown.new(HTML_WITH_IMG, keep_img_tags: true).to_markdown).to eq(HTML_WITH_IMG)
end end
(1..6).each do |n| (1..6).each do |n|