我正在使用红毯宝石来标记用户生成的文本,并希望显示外部链接/图像主机的图像。到目前为止,我已经尝试了这样的东西:
def markdown(text)
options = { ... }
extension = { ... }
text.gsub!(/(https?:\/\/[\S]*.jpg)/, '<img src="\1" width="100%">')
renderer = Redcarpet::Render::HTML.new(options)
markdown = Redcarpet::Markdown.new(renderer, extensions)
markdown.render(text).html_safe
end但是,我更愿意使用escape_html或filter_html,因为注入</div>、id和类确实会使站点变得一团糟。这将删除图像标记。
有没有更好的方法来渲染外部图像,同时保证HTML的安全?
发布于 2016-05-19 06:46:22
如下所示:
require "redcarpet"
require "action_view"
class HTMLBlockCode < Redcarpet::Render::HTML
include ActionView::Helpers::AssetTagHelper
def image(link, title, alt_text)
image_tag(link, title: title, alt: alt_text, width: "100%")
end
end
def markdown(text)
renderer = HTMLBlockCode.new
text.gsub!(/(https?:\/\/[\S]*.jpg)/, '')
markdown = Redcarpet::Markdown.new(renderer)
markdown.render(text)
end
text = File.read("rc_test.md")
puts markdown(text)这将在RedCarpet上安装自定义图像渲染器,该渲染器会将width="100%"属性添加到图像元素。它还在gsub调用中将纯图像链接转换为可标记识别的图像链接。这会导致一个嵌入的图像url呈现如下:
<img width="100%" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" />而且您不必以任何方式更改您的markdown文档;它是自动美味的。
https://stackoverflow.com/questions/37311061
复制相似问题