2016-10-27 27 views
0

我想列出一些HTML标签,例如<kbd></kbd>,这样我就可以为所有键盘快捷键显示漂亮的键盘图标。我怎样才能做到这一点?如何让Redcarpet optionaly过滤HTML标签?

下面的代码片段是我目前用来将Markdown字符串转换为HTML的函数。

def markdown_to_html(markdown_str) 
    options = { 
     filter_html: true, 
     link_attributes: { rel: 'nofollow', target: '_blank' }, 
     no_styles: true 
    } 

    extensions = { 
     autolink: true, 
     fenced_code_blocks: true, 
     footnotes: true, 
     highlight: true, 
     no_intra_emphasis: true, 
     quote: true, 
     space_after_headers: true, 
     strikethrough: true, 
     superscript: true, 
     tables: true 
    } 

    renderer = Redcarpet::Render::HTML.new(options) 
    markdown = Redcarpet::Markdown.new(renderer, extensions) 

    markdown.render(markdown_str).html_safe 
    end 

回答

0

使用sanitize和您自己的自定义scrubber类。

该类可以放在与控制器类相同的文件中。

class MarkdownScrubber < Rails::Html::PermitScrubber 
    def initialize 
    super 
    self.tags = %w(kbd) 
    self.attributes = [] 
    end 

    def skip_node?(node) 
    node.text? 
    end 
end 

然后使用,当你调用render

renderer = Redcarpet::Render::HTML.new(options) 
markdown = Redcarpet::Markdown.new(renderer, extensions) 
sanitize(markdown.render(markdown_str), scrubber: MarkdownScrubber.new) 
+0

我不是'sanitize'可以内部控制器所使用。我得到'sanitize'没有定义错误。谷歌后,我发现'sanitize'是一个ActionView帮手http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html –

+0

@李新阳所以它是。然后,将电话放入您的视图中。 – ArtOfCode