首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Ruby中限制Markdown语法?

如何在Ruby中限制Markdown语法?
EN

Stack Overflow用户
提问于 2010-01-11 15:47:46
回答 1查看 1.1K关注 0票数 9

我希望使用MarakuKramdown等Ruby库在Rails评论系统中实现Markdown。我需要限制哪些Markdown功能的用户可以提交。在这个系统中,用户不允许插入图片、html或执行任何繁重的编辑,但强调和超链接是可以的。

本质上,我希望创建一些类似于this Textile filter的东西,但用于Markdown语法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-01-11 17:56:33

我一直在使用markdown转换之后的第二步,使用sanitize gem清理数据。它基于白名单,可配置性很强,你可以很容易地用它实现你想要的东西。

为了节省你的时间,这里是我的文本格式化模块,希望它能帮到你。内置的宽松规则对我来说有点太严格了。

代码语言:javascript
复制
module TextFormatter
  require 'sanitize'

  module Formatters
    MARKDOWN = 1
    TEXTILE = 2
  end

  RELAXED = {
      :elements => [
        'a', 'b', 'blockquote', 'br', 'caption', 'cite', 'code', 'col',
        'colgroup', 'dd', 'dl', 'dt', 'em', 'i', 'img', 'li', 'ol', 'p', 'pre',
        'q', 'small', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td',
        'tfoot', 'th', 'thead', 'tr', 'u', 'ul', 'del', 'ins', 'h1', 'h2', 'h3', 'h4', 'h5', 'h5', 'hr', 'kbd'],

      :attributes => {
        'a'          => ['href', 'title'],
        'blockquote' => ['cite'],
        'col'        => ['span', 'width'],
        'colgroup'   => ['span', 'width'],
        'img'        => ['align', 'alt', 'height', 'src', 'title', 'width'],
        'ol'         => ['start', 'type'],
        'q'          => ['cite'],
        'table'      => ['summary', 'width'],
        'td'         => ['abbr', 'axis', 'colspan', 'rowspan', 'width'],
        'th'         => ['abbr', 'axis', 'colspan', 'rowspan', 'scope',
                         'width'],
        'ul'         => ['type']
      },

      :protocols => {
        'a'          => {'href' => ['ftp', 'http', 'https', 'mailto',
                                    :relative]},
        'blockquote' => {'cite' => ['http', 'https', :relative]},
        'img'        => {'src'  => ['http', 'https', :relative]},
        'q'          => {'cite' => ['http', 'https', :relative]}
      }
    }



  def self.to_html(text, formatter = Formatters::MARKDOWN)
    return "" unless text

    html = case formatter 
           when Formatters::MARKDOWN then
             RDiscount.new(text, :smart).to_html
           when Formatters::TEXTILE then
             RedCloth.new(text).to_html
           end

    Sanitize.clean(html, RELAXED) 
  end
end
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2040504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档